Home
← All questions

Implement mapLimit: Async Map with a Concurrency Limit in JavaScript

MediumPremiumJavaScript

Asked at Uber · Swiggy

JavaScript interview practice: Apply an async operation across a list while keeping only a few calls running at once, and return results in the same order as the inputs.

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 limit calls in flight at any moment.
  • Resolves with an array of results in input order.
  • Rejects if any iteratee rejects.

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
}
Premium question

Unlock the in-browser editor, test cases, and model solution with Mentoxis Premium.

Unlock with Premium