MCPcopy
hub / github.com/apify/crawlee / chunkedAsyncIterable

Function chunkedAsyncIterable

packages/utils/src/internals/iterables.ts:86–118  ·  view source on GitHub ↗
(
    iterable: AsyncIterable<T> | Iterable<T>,
    chunkSize: number | (() => number),
)

Source from the content-addressed store, hash-verified

84 * ```
85 */
86export async function* chunkedAsyncIterable<T>(
87 iterable: AsyncIterable<T> | Iterable<T>,
88 chunkSize: number | (() => number),
89): AsyncIterable<T[]> {
90 const getChunkSize = typeof chunkSize === 'function' ? chunkSize : () => chunkSize;
91
92 if (typeof chunkSize === 'number' && chunkSize < 1) {
93 throw new Error(`Chunk size must be a positive number (${inspect(chunkSize)}) received`);
94 }
95
96 const iterator =
97 Symbol.asyncIterator in iterable
98 ? (iterable as AsyncIterable<T>)[Symbol.asyncIterator]()
99 : (iterable as Iterable<T>)[Symbol.iterator]();
100
101 while (true) {
102 const currentSize = getChunkSize();
103 if (currentSize < 1) break;
104
105 const chunk: T[] = [];
106
107 for (let i = 0; i < currentSize; i++) {
108 const next = await iterator.next();
109 if (next.done) {
110 break;
111 }
112 chunk.push(next.value);
113 }
114
115 if (chunk.length === 0) break;
116 yield chunk;
117 }
118}
119
120/**
121 * An async iterator that also supports peeking at the next value without consuming it.

Callers 2

addRequestsBatchedFunction · 0.90
iterables.test.tsFile · 0.90

Calls 1

pushMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…