Skip to content

Commit

Permalink
Refactor chunk function to handle edge cases
Browse files Browse the repository at this point in the history
  • Loading branch information
klarstrup committed Sep 6, 2024
1 parent 1d04c06 commit 351f1c8
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
45 changes: 45 additions & 0 deletions lib/util.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { chunk } from './util';

describe('chunk', () => {
it('should split an array into chunks of the specified size', () => {
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const size = 3;
const result = chunk(arr, size);
expect(result).toEqual([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
});

it('should handle arrays that do not divide evenly by the chunk size', () => {
const arr = [1, 2, 3, 4, 5, 6, 7];
const size = 3;
const result = chunk(arr, size);
expect(result).toEqual([[1, 2, 3], [4, 5, 6], [7]]);
});

it('should return an empty array when given an empty array', () => {
const arr: number[] = [];
const size = 3;
const result = chunk(arr, size);
expect(result).toEqual([]);
});

it('should handle chunk sizes larger than the array length', () => {
const arr = [1, 2, 3];
const size = 5;
const result = chunk(arr, size);
expect(result).toEqual([[1, 2, 3]]);
});

it('should handle chunk size of 1', () => {
const arr = [1, 2, 3];
const size = 1;
const result = chunk(arr, size);
expect(result).toEqual([[1], [2], [3]]);
});

it('should handle chunk size of 0', () => {
const arr = [1, 2, 3];
const size = 0;
const result = chunk(arr, size);
expect(result).toEqual([]);
});
});
3 changes: 3 additions & 0 deletions lib/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,9 @@ export function debounce<A extends unknown[]>(
export function chunk<I extends any>(arr: I[], size: number) {
const results: I[][] = [];

if (!arr.length) return results;
if (size <= 0) return results;

while (arr.length) results.push(arr.splice(0, size));

return results;
Expand Down

0 comments on commit 351f1c8

Please sign in to comment.