Functional Weave
Code in Python

collections.chunk@1.0.0

impl/typescript.ts

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.
 */
export function chunk<T>(items: readonly T[], size: number): readonly (readonly T[])[] {
  if (!Array.isArray(items)) {
    throw new TypeError("chunk needs a list of items");
  }
  if (!Number.isInteger(size)) {
    throw new TypeError(`size must be a whole number, received ${size}`);
  }
  if (size < 1) {
    throw new 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;
}