Task Scheduler with Priority
Problem statement
Implement a small TaskScheduler class with concurrency and priority support.
API
const scheduler = new TaskScheduler(2);
scheduler.add(() => fetch('/a'), { priority: 10 });
scheduler.add(() => fetch('/b'), { priority: 1 });
Requirements
- The constructor receives
concurrency. add(task, options)returns a promise for that task's result.- Run at most
concurrencytasks at once. - Higher priority tasks should start before lower priority queued tasks.
- For equal priority, preserve FIFO order.
- Support synchronous return values, async results, and thrown errors.
This is a senior-style async question because it combines queue modeling, promise resolution, fairness, and concurrency control.
Requirements & constraints
- Do not run more than `concurrency` tasks at once.
- Higher priority means earlier start, not preemption of already-running tasks.
- Preserve FIFO ordering for same priority.
How to approach Task Scheduler with Priority
The strategy an interviewer expects you to reach for.
A priority task scheduler is a promise pool with a queue: VIP work jumps ahead without starving concurrency rules. Naive move Always await tasks in arrival order, or sort the whole queue on every insert without a stable tie-break. Where it breaks Equal priorities should keep FIFO order. Finishing a task must drain the highest waiting work up to concurrency. The fix Enqueue {priority, seq, task, resolve, reject}. On add/finish, _drain: while running < concurrency, pop best priority (then lowest seq), run it, settle its promise. Remember: Priority first, insertion sequence second — stable under ties. Say this in the interview: I'd queue tasks with priority and a monotonic sequence, then drain into a fixed concurrency limit so higher priorities run first while equal priorities stay FIFO.
The full solution is part of HelloFrontend Pro
The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.
- Runnable editor with the hidden test suite
- Progressive hints that unlock as you get stuck
- Senior-level reference solution with a line-by-line walkthrough
Already a member? Log in to open the workspace.