CodePark/ problems / Map with limited concurrency
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › Async control flow

Map with limited concurrency

hardabout 30 minutes in an interview

Implement mapAsyncLimit(items, fn, limit). fn(item, index) returns a promise. Run fn on every item, but with at most limit calls in flight at any moment. A call is in flight from when it starts until its promise settles.

  • Start the first limit items right away, or all of them if there are fewer.
  • As soon as any call finishes, start the next item that hasn't started yet. Don't wait for a whole group to finish.
  • Resolve with the results in input order.
  • An empty array resolves to [] without calling fn.
  • If any call rejects, reject with that error straight away and start no more items. Calls that are already running may finish, but their results are ignored.
  • limit is a positive integer.
Input: await mapAsyncLimit([1, 2, 3, 4], async n => n * 10, 2) Output: [10, 20, 30, 40]
Input: delays [100, 10, 10, 10] ms, limit 2 Output: item 2 starts at 10 ms and item 3 at 20 ms, while item 0 is still runningA freed slot is reused at once.