Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c14bd52
commit 88fdc10
Showing
3 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
|
||
/** | ||
* | ||
* Splits an array into smaller arrays of a specified size. | ||
* | ||
* @example chunk(["A", "B", "C", "D", "E", "F", "G"], 2); // [["A", "B"], ["C", "D"], ["E", "F"], ["G"]] | ||
* | ||
* @param {any[]} array | ||
* @param {number} size | ||
* @returns | ||
* | ||
* @function chunk | ||
* @memberof Arrays | ||
*/ | ||
export function chunk(array, size = 1) { | ||
const chunkedArray = []; | ||
|
||
for (let i = 0; i < array.length; i += size) { | ||
chunkedArray.push(array.slice(i, i + size)); | ||
} | ||
|
||
return chunkedArray; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
import { Arrays } from "../../src/index.js"; | ||
const { chunk } = Arrays; | ||
|
||
describe("Arrays/chunk.js", () => { | ||
it("should split an array into smaller arrays of specified size", () => { | ||
const array = [1, 2, 3, 4, 5, 6]; | ||
const expected = [[1, 2], [3, 4], [5, 6]]; | ||
expect(chunk(array, 2)).toEqual(expected); | ||
}); | ||
|
||
it("should split an array into smaller arrays of size 1 by default", () => { | ||
const array = ["a", "b", "c", "d"]; | ||
const expected = [["a"], ["b"], ["c"], ["d"]]; | ||
expect(chunk(array)).toEqual(expected); | ||
}); | ||
|
||
it("should return an empty array if the input array is empty", () => { | ||
const array = []; | ||
const expected = []; | ||
expect(chunk(array, 3)).toEqual(expected); | ||
}); | ||
}); |