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;
}Report a problem with this exampleOpens a pre-filled issue on GitHub.