JavaScript

Yield array batches with a generator

Use a generator to yield slices of an array a batch at a time. Consumers can process one batch before requesting the next instead of first constructing an array containing every batch.

Worked example

Node.js example · save as example.mjs and run node example.mjs

function* batches(items, size) {
  if (!Number.isInteger(size) || size < 1) throw new Error("Invalid batch size");
  for (let start = 0; start < items.length; start += size) {
    yield items.slice(start, start + size);
  }
}
console.log(JSON.stringify([...batches([1, 2, 3, 4, 5], 2)]));

How it works

Yield pauses the generator after each slice. A for...of consumer can await work on the batch before continuing. The final batch may be shorter than the requested size, so consumers should not assume a constant number of records.

Limits and mistakes

The original array still resides in memory, and each slice is a shallow copy. Spreading the generator, as shown for display, collects all batches and removes the incremental-consumption benefit. Stream the input too when the entire dataset is large.

Check the result

Expect [[1,2],[3,4],[5]]. Test empty input, a size larger than the array, and an invalid zero size to prevent a non-advancing loop.

Sources

Reference documentation for the behavior used in this guide: