frontend-challenges icon indicating copy to clipboard operation
frontend-challenges copied to clipboard

86 - Chunk - javascript

Open jsartisan opened this issue 1 year ago • 0 comments

index.js

export function chunk(array, size) {
  const result = [];

  if (!Array.isArray(array)) throw TypeError("first argument is not an array");

  if (!(typeof size === "number" && size > 0))
    throw TypeError("econd argument is not a positive number");

  for (let i = 0; i < array.length; i++) {
    const last = result.at(-1);
    const current = array[i];

    if (Array.isArray(last) && last.length < size) {
      last.push(current);
      result[result.length - 1] = last;
    } else {
      result.push([current]);
    }
  }

  return result;
}

jsartisan avatar Jun 19 '24 06:06 jsartisan