(
iterable: AsyncIterable<T> | Iterable<T>,
chunkSize: number | (() => number),
)
| 84 | * ``` |
| 85 | */ |
| 86 | export 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. |
no test coverage detected
searching dependent graphs…