diff --git a/lib/util.test.ts b/lib/util.test.ts new file mode 100644 index 00000000..67ee0d91 --- /dev/null +++ b/lib/util.test.ts @@ -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([]); + }); +}); \ No newline at end of file diff --git a/lib/util.ts b/lib/util.ts index 9f13e6ba..6e3d5850 100644 --- a/lib/util.ts +++ b/lib/util.ts @@ -93,6 +93,9 @@ export function debounce( export function chunk(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;