Write chunk(array, size). It returns a new array of groups: the first size items of array, then the next size items, and so on. The last group holds whatever is left, so it can be shorter.
size must be a positive integer. For anything else, such as 0, -1, 1.5, or NaN, throw a RangeError.
An empty array gives []. Every group is a new array holding the same items as array, and array itself never changes.
chunk([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]]
chunk([1, 2, 3, 4], 2); // [[1, 2], [3, 4]]
chunk([1, 2, 3], 5); // [[1, 2, 3]]
chunk([], 3); // []
chunk([1, 2], 0); // throws a RangeError
expect(chunk([1, 2, 3, 4, 5, 6], 3)).toEqual([[1, 2, 3], [4, 5, 6]]);
expect(chunk(["a", "b", "c"], 1)).toEqual([["a"], ["b"], ["c"]]);
expect(chunk([1, 2, 3, 4, 5], 2)).toEqual([[1, 2], [3, 4], [5]]);
const groups = chunk([1, 2, 3, 4], 2);
expect(groups).toHaveLength(2);
expect(groups).toEqual([[1, 2], [3, 4]]);
expect(chunk([1, 2, 3], 5)).toEqual([[1, 2, 3]]);
expect(chunk([], 3)).toEqual([]);
for (const size of [1.5, NaN, -1, 0]) {
let thrown;
try {
chunk([1, 2], size);
} catch (error) {
thrown = error;
}
// The page stops a loop that never ends with an InfiniteLoopError, which is a RangeError too, so report it here.
if (thrown?.name === "InfiniteLoopError") throw new Error("chunk([1, 2], " + size + ") never finished: " + thrown.message);
expect(thrown).toBeInstanceOf(RangeError);
}
const item = { id: 1 };
const input = [item, 2, 3];
const groups = chunk(input, 5);
expect(groups[0]).not.toBe(input);
expect(groups[0][0]).toBe(item);
chunk(input, 2);
expect(input).toEqual([{ id: 1 }, 2, 3]);
expect(input).toHaveLength(3);
Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.
Ctrl + Enter runs the tests (⌘ + Enter on a Mac).
I'm here to help with Chunk an array. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.