( generators: AsyncGenerator<A, void>[], concurrencyCap = Infinity, )
| 30 | |
| 31 | // Run all generators concurrently up to a concurrency cap, yielding values as they come in |
| 32 | export async function* all<A>( |
| 33 | generators: AsyncGenerator<A, void>[], |
| 34 | concurrencyCap = Infinity, |
| 35 | ): AsyncGenerator<A, void> { |
| 36 | const next = (generator: AsyncGenerator<A, void>) => { |
| 37 | const promise: Promise<QueuedGenerator<A>> = generator |
| 38 | .next() |
| 39 | .then(({ done, value }) => ({ |
| 40 | done, |
| 41 | value, |
| 42 | generator, |
| 43 | promise, |
| 44 | })) |
| 45 | return promise |
| 46 | } |
| 47 | const waiting = [...generators] |
| 48 | const promises = new Set<Promise<QueuedGenerator<A>>>() |
| 49 | |
| 50 | // Start initial batch up to concurrency cap |
| 51 | while (promises.size < concurrencyCap && waiting.length > 0) { |
| 52 | const gen = waiting.shift()! |
| 53 | promises.add(next(gen)) |
| 54 | } |
| 55 | |
| 56 | while (promises.size > 0) { |
| 57 | const { done, value, generator, promise } = await Promise.race(promises) |
| 58 | promises.delete(promise) |
| 59 | |
| 60 | if (!done) { |
| 61 | promises.add(next(generator)) |
| 62 | // TODO: Clean this up |
| 63 | if (value !== undefined) { |
| 64 | yield value |
| 65 | } |
| 66 | } else if (waiting.length > 0) { |
| 67 | // Start a new generator when one finishes |
| 68 | const nextGen = waiting.shift()! |
| 69 | promises.add(next(nextGen)) |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | export async function toArray<A>( |
| 75 | generator: AsyncGenerator<A, void>, |
no test coverage detected