From b8243dc89d20a979afdd42e24e309e53ff58c844 Mon Sep 17 00:00:00 2001 From: Tuyen Nguyen Date: Mon, 18 Sep 2023 17:11:36 +0700 Subject: [PATCH] chore: support index -1 --- packages/ssz/src/viewDU/listBasic.ts | 16 +++++++++++++++- .../ssz/test/unit/byType/listBasic/tree.test.ts | 10 +++++++--- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/packages/ssz/src/viewDU/listBasic.ts b/packages/ssz/src/viewDU/listBasic.ts index 7d2c509b..d269fd76 100644 --- a/packages/ssz/src/viewDU/listBasic.ts +++ b/packages/ssz/src/viewDU/listBasic.ts @@ -38,12 +38,26 @@ export class ListBasicTreeViewDU> extends this.set(index, value); } + /** + * Returns a new ListBasicTreeViewDU instance with the values from 0 to `index`. + * To achieve it, rebinds the underlying tree zero-ing all nodes right of `chunkIindex`. + * Also set all value right of `index` in the same chunk to 0. + * + * Note: Using index = -1, returns an empty list of length 0. + */ sliceTo(index: number): this { + if (index < -1) { + throw new Error("Does not support sliceTo() with index less than -1"); + } + + if (index === -1) { + return this.type.defaultViewDU() as this; + } + // Commit before getting rootNode to ensure all pending data is in the rootNode this.commit(); // All nodes beyond length are already zero - // Array of length 2: [X,X,0,0], for index >= 1 no action needed if (index >= this._length - 1) { return this; } diff --git a/packages/ssz/test/unit/byType/listBasic/tree.test.ts b/packages/ssz/test/unit/byType/listBasic/tree.test.ts index e6b15672..719e61ff 100644 --- a/packages/ssz/test/unit/byType/listBasic/tree.test.ts +++ b/packages/ssz/test/unit/byType/listBasic/tree.test.ts @@ -219,13 +219,17 @@ describe("ListBasicType.sliceTo", () => { const listRoots: string[] = []; const listSerialized: string[] = []; - for (let i = 0; i < 16; i++) { - listView.push(i); + for (let i = -1; i < 16; i++) { + if (i >= 0) { + listView.push(i); + } + // Javascript arrays can handle negative indexes (ok for tests) listSerialized[i] = toHexString(listView.serialize()); listRoots[i] = toHexString(listView.hashTreeRoot()); } - for (let i = 0; i < 16; i++) { + // Start at -1 to test the empty case. + for (let i = -1; i < 16; i++) { const listSlice = listView.sliceTo(i); expect(listSlice.length).to.equal(i + 1, `Wrong length at .sliceTo(${i})`); expect(toHexString(listSlice.serialize())).equals(listSerialized[i], `Wrong serialize at .sliceTo(${i})`);