Problem
You have hundreds of image URLs to process. Starting every request at once will exhaust sockets and trip rate limits. You want to keep only N operations running at a time — when one finishes, start the next — and still get results back in the original input 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
}