Batch Items From Async Iterables
Group values from async iterables into fixed-size arrays, yielding full batches and a final partial batch without buffering all.
Code
export async function* batchAsync<T>(
source: AsyncIterable<T> | Iterable<T>,
size: number,
): AsyncGenerator<T[], void, void> {
if (!Number.isInteger(size) || size < 1) {
throw new RangeError("size must be a positive integer");
}
if (source === null || source === undefined) {
throw new TypeError("source must be iterable");
}
let batch: T[] = [];
for await (const item of source) {
batch.push(item);
if (batch.length === size) {
yield batch;
batch = [];
}
}
if (batch.length > 0) yield batch;
}
export async function collectBatches<T>(
source: AsyncIterable<T> | Iterable<T>,
size: number,
): Promise<T[][]> {
const output: T[][] = [];
for await (const batch of batchAsync(source, size)) output.push(batch);
return output;
}How it works
Batch Items From Async Iterables comes down to the function collectBatches.
The structure is a loop within a loop: for await (const item of source) outside, for await (const batch of batchAsync(source, size)) output.push(batch); inside. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Failure is loud: RangeError and TypeError aborts the current operation instead of degrading it.
What to watch for
- The guard
source === null || source === undefinedshort-circuits the flow with an earlythrowwhen its condition holds.
Using it
batchAsync is what another module would consume; nothing else here is load-bearing for callers.
Key statements
for await (const batch of batchAsync(source, size)) output.push(batch);
throw new RangeError("size must be a positive integer");
throw new TypeError("source must be iterable");
FAQ
- What does the snippet do with malformed data?
- `RangeError` and `TypeError` is raised at the guard (`source === null || source === undefined`), so invalid state never reaches the main logic.
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. The file defines `collectBatches` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.