Problem
You have 500 image URLs to process, but firing 500 requests at once will exhaust sockets and trip rate limits. You want to process them N at a time — start the next as soon as one finishes — while still getting results back in the original order.
Implement mapLimit(inputs, limit, iteratee) that:
- Calls
iteratee(input)(returns a promise) for each input. - Keeps at most
limitcalls in flight at any moment. - Resolves with an array of results in input order.
- Rejects if any
iterateerejects.
Input
const asyncDouble = (n) =>
new Promise((res) => setTimeout(() => res(n * 2), 100));
mapLimit([1, 2, 3, 4, 5], 2, asyncDouble).then(console.log);
Expected output
[2, 4, 6, 8, 10]— with never more than 2 running at once.
Implement from scratch:
function mapLimit(inputs, limit, iteratee) {
// Your code here
}