Skip to content

Commit

Permalink
feat: add helper to split an array into sized groups
Browse files Browse the repository at this point in the history
  • Loading branch information
thislooksfun committed Mar 12, 2021
1 parent 2da716c commit ffbe5b1
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/helper/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,13 @@ export function camelCaseKeys<T>(obj: Data): T {
}
return out as T;
}

export function group<T>(arr: T[], size: number): T[][] {
const groups: T[][] = [];
const count = Math.ceil(arr.length / size);
for (let i = 0; i < count; ++i) {
groups.push(arr.slice(i * size, (i + 1) * size));
}

return groups;
}
25 changes: 25 additions & 0 deletions test/helper/util.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,28 @@ describe("camelCaseKeys()", () => {
expect(util.camelCaseKeys(a)).toStrictEqual(b);
});
});

describe("group()", () => {
it("should split an array into groups", () => {
const a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const b = [
[1, 2],
[3, 4],
[5, 6],
[7, 8],
[9, 10],
];

expect(util.group(a, 2)).toStrictEqual(b);
});

it("should put the remainder into a group", () => {
const a = [1, 2, 3, 4, 5];
const b = [
[1, 2, 3],
[4, 5],
];

expect(util.group(a, 3)).toStrictEqual(b);
});
});

0 comments on commit ffbe5b1

Please sign in to comment.