Skip to content

Commit

Permalink
feat: add chunk array
Browse files Browse the repository at this point in the history
  • Loading branch information
201flaviosilva committed May 19, 2023
1 parent c14bd52 commit 88fdc10
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/Arrays/chunk.js
@@ -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;
}
2 changes: 2 additions & 0 deletions src/Arrays/index.js
@@ -1,5 +1,6 @@
import { allEqual } from "./allEqual.js";
import { choice } from "./choice.js";
import { chunk } from "./chunk.js";
import { findBigObject } from "./findBigObject.js";
import { findLowObject } from "./findLowObject.js";
import { isSorted } from "./isSorted.js";
Expand All @@ -18,6 +19,7 @@ import { sortDescendingObject } from "./sortDescendingObject.js";
export {
allEqual,
choice,
chunk,
findBigObject,
findLowObject,
isSorted,
Expand Down
22 changes: 22 additions & 0 deletions tests/Arrays/chunk.test.js
@@ -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);
});
});

0 comments on commit 88fdc10

Please sign in to comment.