Array Chunking With Size Validation

Split arrays or any iterable into fixed-size chunks with strict size validation, ordered output and a lazy generator variant.

JavascriptData Integrity

Code

javascriptsnippet
31 lines
function assertSize(size) {
  if (!Number.isInteger(size) || size < 1) {
    throw new RangeError("size must be a positive integer");
  }
}

export function chunk(array, size) {
  if (!Array.isArray(array)) throw new TypeError("array must be an array");
  assertSize(size);
  const chunks = [];
  for (let index = 0; index < array.length; index += size) {
    chunks.push(array.slice(index, index + size));
  }
  return chunks;
}

export function* chunkLazy(iterable, size) {
  assertSize(size);
  if (iterable === null || typeof iterable[Symbol.iterator] !== "function") {
    throw new TypeError("iterable must implement Symbol.iterator");
  }
  let bucket = [];
  for (const item of iterable) {
    bucket.push(item);
    if (bucket.length === size) {
      yield bucket;
      bucket = [];
    }
  }
  if (bucket.length > 0) yield bucket;
}

How the snippet works

Count the functions assertSize and chunk as the entire surface area of Array Chunking With Size Validation.

Iteration is nested: for (let index = 0; index < array.length; index += size) frames the pass, for (const item of iterable) does the per-item step. RangeError and TypeError is the guard’s signal — thrown at the branch, before any partial work happens.

Caveats

  • The guard iterable === null || typeof iterable[Symbol.iterator] !== "function" short-circuits the flow with an early throw when its condition holds.

Applying it

Signature: export function chunk(array, size)

chunk is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

if (!Array.isArray(array)) throw new TypeError("array must be an array");
throw new TypeError("iterable must implement Symbol.iterator");
for (let index = 0; index < array.length; index += size) {
chunks.push(array.slice(index, index + size));
}

Interactive Tools for This Topic

FAQ

How does the code behave when input is bad?
The code refuses to continue: `RangeError` and `TypeError` is thrown while the state is still recoverable.
Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. The file defines `assertSize`, `chunk` at load time.