Skip to the solution
MediumFrontendAsked in 20246 min read

Async map limit concurrency

1.0k views

The problem

Problem, as an interviewer would state it: "Implement mapLimit(items, limit, mapper) — like Array.prototype.map, but mapper is async, and no more than limit calls should ever run concurrently, while the FINAL results array still preserves the original input order."

Examples:

Code
await mapLimit([1,2,3,4,5], 2, async (n) => n * 10); // [10,20,30,40,50], never more than 2 running at once

Clarifying questions expected:

  • Must the RESULTS array preserve original input order, even though the underlying calls may COMPLETE out of order?
  • Should one item's mapper rejecting stop the whole operation immediately, or let already-started items finish first?
  • Is this conceptually the same underlying mechanism as this bank own p-limit question?

Code / implementation expected: Yes — real, direct proof via a logged execution trace that concurrency stays capped at the limit, and that results preserve original order despite items completing at different times.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: mapLimit() preserves original input order in its results while a logged execution trace confirms concurrency stays capped at the limit

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 87 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Design a Simple In-Memory Key-Value Store With TTL Expiry (Mini-Redis)

Continue