Build a Task Queue with Pause and Resume

Write the code, see it run, pass the checks.

The problem

  • hard
  • Code
  • Pro

Write a class TaskQueue. new TaskQueue(concurrency) makes an empty queue that runs at most concurrency tasks at once. add(task), where task is a function that takes no arguments and returns a promise, returns a promise that settles the same way task's does. Tasks start in the order they were added; one added while a slot is free and the queue isn't paused starts at once, during the add call. pause() stops any more tasks starting, while running ones carry on; resume() starts waiting tasks again, up to the limit. onIdle() returns a promise that resolves once nothing is running and nothing is waiting, straight away if that's already so; a paused queue with tasks waiting isn't idle. Two read-only properties report the counts: size is how many tasks are waiting, and pending how many are running. A task that rejects frees its slot like any other.

Your code must pass

  • Runs tasks in order, at most concurrency at once
  • Passes each task's result or rejection to its caller
  • Pause stops new tasks starting; resume starts them again
  • onIdle resolves once every task has finished
  • Reports waiting and running counts