diff --git a/packages/prover/src/utils/conversion.ts b/packages/prover/src/utils/conversion.ts index b26b1852ed74..1f143baf1bda 100644 --- a/packages/prover/src/utils/conversion.ts +++ b/packages/prover/src/utils/conversion.ts @@ -97,12 +97,11 @@ export function cleanObject | unknown[]>(obj: } /** - * Convert an array to array of chunks + * Convert an array to array of chunks of length N * @example - * chunkIntoN([1,2,3,4], 2) - * => [[1,2], [3,4]] + * chunkIntoN([1,2,3,4,5,6], 2) + * => [[1,2], [3,4], [5,6]] */ export function chunkIntoN(arr: T, n: number): T[] { - const size = Math.ceil(arr.length / n); - return Array.from({length: n}, (v, i) => arr.slice(i * size, i * size + size)) as T[]; + return Array.from({length: Math.ceil(arr.length / n)}, (_, i) => arr.slice(i * n, i * n + n)) as T[]; } diff --git a/packages/prover/test/unit/utils/conversion.test.ts b/packages/prover/test/unit/utils/conversion.test.ts new file mode 100644 index 000000000000..50ed03a89450 --- /dev/null +++ b/packages/prover/test/unit/utils/conversion.test.ts @@ -0,0 +1,86 @@ +import {expect} from "chai"; +import {chunkIntoN} from "../../../src/utils/conversion.js"; + +describe("utils/conversion", () => { + describe("chunkIntoN", () => { + const testCases = [ + { + title: "even number of chunks", + input: { + data: [1, 2, 3, 4, 5, 6], + n: 2, + }, + output: [ + [1, 2], + [3, 4], + [5, 6], + ], + }, + { + title: "even number of chunks with additional element", + input: { + data: [1, 2, 3, 4, 5, 6, 7], + n: 2, + }, + output: [[1, 2], [3, 4], [5, 6], [7]], + }, + { + title: "odd number of chunks", + input: { + data: [1, 2, 3, 4, 5, 6], + n: 3, + }, + output: [ + [1, 2, 3], + [4, 5, 6], + ], + }, + { + title: "odd number of chunks with additional element", + input: { + data: [1, 2, 3, 4, 5, 6, 7], + n: 3, + }, + output: [[1, 2, 3], [4, 5, 6], [7]], + }, + { + title: "data less than chunk size", + input: { + data: [1], + n: 3, + }, + output: [[1]], + }, + { + title: "data 1 less than chunk size", + input: { + data: [1, 2], + n: 3, + }, + output: [[1, 2]], + }, + { + title: "data 1 extra than chunk size", + input: { + data: [1, 2, 3, 4], + n: 3, + }, + output: [[1, 2, 3], [4]], + }, + ]; + + for (const {title, input, output} of testCases) { + it(`should chunkify data when ${title}`, async () => { + expect(chunkIntoN(input.data, input.n)).to.be.deep.eq(output); + }); + } + + it("should not change the order of elements", () => { + expect(chunkIntoN([6, 5, 4, 3, 2, 1], 2)).to.be.deep.eq([ + [6, 5], + [4, 3], + [2, 1], + ]); + }); + }); +});