Write `mapWithConcurrency(items, fn, concurrency)` that processes items with fn (async) but limits concurrent executions.
Problem Statement
Write `mapWithConcurrency(items, fn, concurrency)` that processes items with fn (async) but limits concurrent executions.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
Process items in batches or use a pool pattern.
š” Hint 2:
Track active promises and start new ones as old ones complete.
š” Hint 3:
Use an index counter and recursive next() function to control flow.
ā
Solution:
```javascript
async function mapWithConcurrency(items, fn, concurrency) {
const results = new Array(items.length);
let index = 0;
async function worker() {
while (index < items.length) {
const i = index++;
results[i] = await fn(items[i]);
}
}
const workers = Array.from({ length: Math.min(concurrency, items.length) }, () => worker());
await Promise.all(workers);
return results;
}
```