jsartisan / frontend-challenges

FrontendChallenges is a collection of frontend interview questions and answers. It is designed to help you prepare for frontend interviews. It's free and open source.
https://frontend-challenges.com
27 stars 4 forks source link

86 - Chunk - javascript #90

Open jsartisan opened 3 months ago

jsartisan commented 3 months ago

index.js

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

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

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

  for (let i = 0; i < array.length; i += size) {
    chunkedArray.push(array.slice(i, i + size));
  }

  return chunkedArray;
}