( items: T[], fn: (item: T, index: number) => Promise<R>, concurrency = 10, )
| 15 | * const results = await mapWithConcurrency(urls, fetchUrl, 5) |
| 16 | */ |
| 17 | export async function mapWithConcurrency<T, R>( |
| 18 | items: T[], |
| 19 | fn: (item: T, index: number) => Promise<R>, |
| 20 | concurrency = 10, |
| 21 | ): Promise<R[]> { |
| 22 | const results: R[] = Array.from({ length: items.length }) as R[] |
| 23 | let currentIndex = 0 |
| 24 | |
| 25 | async function worker(): Promise<void> { |
| 26 | while (currentIndex < items.length) { |
| 27 | const index = currentIndex++ |
| 28 | results[index] = await fn(items[index]!, index) |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | // Start workers up to concurrency limit |
| 33 | const workers = Array.from({ length: Math.min(concurrency, items.length) }, () => worker()) |
| 34 | await Promise.all(workers) |
| 35 | |
| 36 | return results |
| 37 | } |
no test coverage detected