Skip to content
Onsite

Async Concurrency Limiter

HardP1Coding

Implement runWithLimit(tasks, limit).

tasks is an array of functions; each takes no arguments and returns a promise (or a plain value). runWithLimit starts them so that at most limit tasks are running at the same time, and returns a promise that:

  • resolves with an array of the results in the order of tasks, once every task has finished,
  • rejects with the reason of the first task that fails; after that, no further tasks are started,
  • resolves with [] when tasks is empty.

As soon as a running task finishes, the next waiting task must start (do not wait for a whole batch).

Example 1

Input
runWithLimit([t1, t2, t3, t4], 2)
Output
t1 and t2 start first; t3 starts when one of them finishes; results come back as [r1, r2, r3, r4]

Constraints

  • 0 <= tasks.length <= 10^4
  • 1 <= limit <= 10^4 (limit larger than tasks.length is fine)
  • Do not call a task before a slot is free

Hints

Run checks the 3 visible tests, Submit all 9.