Run Async Jobs by Priority

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

The problem

  • medium
  • Code

Write createPriorityRunner(concurrency), returning an object with a method add(task, priority). task is a function that takes no arguments and returns a promise, and priority is a number, higher meaning more urgent. Run at most concurrency tasks at once. A task added while a slot is free starts at once, during the add call. Otherwise it waits, and whenever a running task finishes, start the waiting task with the highest priority; among equal priorities, the one added first. add returns a promise that settles the same way the task's own promise does. A task that rejects frees its slot like any other, and the runner keeps going.

Your code must pass

  • Starts tasks at once while a slot is free
  • Never runs more than concurrency tasks at once
  • Starts the highest priority waiting task next
  • Starts equal priorities in the order they were added
  • Passes each task's result or rejection on and keeps going