858 bytes · the TypeScript implementation · view raw
/** * Split `items` into consecutive batches of at most `size`, in order. * * An empty list gives no batches rather than one empty batch, so a loop over * the result never sends an empty request. A size below 1 throws: it is * always a bug upstream, and "no limit" is the outage batching prevents. */exportfunction chunk<T>(items: readonly T[], size: number): readonly (readonly T[])[] {
if (!Array.isArray(items)) {
thrownew TypeError("chunk needs a list of items");
}
if (!Number.isInteger(size)) {
thrownew TypeError(`size must be a whole number, received ${size}`);
}
if (size < 1) {
thrownew RangeError(`size must be at least 1, received ${size}`);
}
const batches: T[][] = [];
for (let start = 0; start < items.length; start += size) {
batches.push(items.slice(start, start + size));
}
return batches;
}