Skip to content

Commit

Permalink
feat(essentials): chunk
Browse files Browse the repository at this point in the history
  • Loading branch information
thijsdaniels committed Jun 13, 2024
1 parent b84679c commit 6a38196
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 9 deletions.
5 changes: 5 additions & 0 deletions .changeset/empty-wasps-itch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@codedazur/essentials": minor
---

The array chunk utility was added.
22 changes: 13 additions & 9 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

40 changes: 40 additions & 0 deletions packages/essentials/utilities/array/chunk.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { describe, expect, it } from "vitest";
import { chunk } from "./chunk";

describe("chunk", () => {
it("should chunk an array into smaller arrays", () => {
const array = [1, 2, 3, 4];
const chunkedArray = chunk(array, 2);
expect(chunkedArray).toEqual([
[1, 2],
[3, 4],
]);
});

it("should handle an empty array", () => {
expect(chunk([], 2)).toEqual([]);
});

it("should handle remainders", () => {
const array = [1, 2, 3, 4, 5];
const chunkedArray = chunk(array, 3);
expect(chunkedArray).toEqual([
[1, 2, 3],
[4, 5],
]);
});

it("should not modify the original array", () => {
const array = [1, 2, 3, 4];
chunk(array, 2);
expect(array).toEqual([1, 2, 3, 4]);
});

it("should throw an error when given a size of 0", () => {
expect(() => chunk([1, 2, 3, 4], 0)).toThrow();
});

it("should throw an error when given a negative size", () => {
expect(() => chunk([1, 2, 3, 4], -1)).toThrow();
});
});
14 changes: 14 additions & 0 deletions packages/essentials/utilities/array/chunk.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { assert } from "../assert";

export function chunk<T>(array: T[], size: number): T[][] {
assert(size > 0, "Size must be greater than 0.");

if (!array.length) {
return [];
}

const head = array.slice(0, size);
const tail = array.slice(size);

return [head, ...chunk(tail, size)];
}

0 comments on commit 6a38196

Please sign in to comment.