Overview
Implement mapAsyncLimit(array, limit, asyncFn) that runs at most limit async operations concurrently.
Constraints
- Max
limitconcurrent operations at any time - Order of results matches input order
Examples
await mapAsyncLimit([1,2,3,4], 2, async x => x * 2); // [2,4,6,8]
Solution
Reveal solution
async function mapAsyncLimit(array, limit, asyncFn) {
const results = new Array(array.length);
let idx = 0;
async function worker() {
while (idx < array.length) {
const i = idx++;
results[i] = await asyncFn(array[i]);
}
}
const workers = Array.from({ length: Math.min(limit, array.length) }, () => worker());
await Promise.all(workers);
return results;
}map-async-limit.js
Map Async Limit
mediumcodingJavaScriptPromises
Overview
Implement mapAsyncLimit(array, limit, asyncFn) that runs at most limit async operations concurrently.
Constraints
- Max
limitconcurrent operations at any time - Order of results matches input order
Examples
await mapAsyncLimit([1,2,3,4], 2, async x => x * 2); // [2,4,6,8]
Solution
Reveal solution
async function mapAsyncLimit(array, limit, asyncFn) {
const results = new Array(array.length);
let idx = 0;
async function worker() {
while (idx < array.length) {
const i = idx++;
results[i] = await asyncFn(array[i]);
}
}
const workers = Array.from({ length: Math.min(limit, array.length) }, () => worker());
await Promise.all(workers);
return results;
}NameTopicDifficulty
103 of 103 problems