Build a counting semaphore
A pool works when you already have the full list of tasks. When work arrives over time — a user clicking upload repeatedly — you need a permit you can acquire from anywhere and release when done.
Implement a class Semaphore. new Semaphore(max) allows max holders at once. acquire() returns a promise; it resolves immediately if fewer than max permits are held, and otherwise waits until one is released. It resolves with a release function that gives the permit back and hands it to the longest-waiting caller, in first-in-first-out order. Calling a release function more than once has no effect beyond the first call, so a double release can never let an extra caller through.
What it has to do
- Allow at most
maxholders at any time. - Resolve
acquire()immediately while permits are free. - Hand a released permit to waiters in FIFO order.
- Resolve with a
releasefunction rather than a plain value. - Make
releaseidempotent: extra calls do nothing.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.