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.
Code
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 earlythrowwhen 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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.