Explorer
Node.js

Implement an `AsyncQueue` with a concurrency limit. `add(task)` queues tasks. No more than `concurrency` tasks run simultaneously.

Problem Statement

Implement an `AsyncQueue` with a concurrency limit. `add(task)` queues tasks. No more than `concurrency` tasks run simultaneously.

Complexity

Time Complexity: -

Space Complexity: -

Hints

šŸ’” Hint 1: Track running count and pending tasks in a queue. šŸ’” Hint 2: When a task finishes, check if there are pending tasks to start. šŸ’” Hint 3: Use a recursive processQueue pattern that starts tasks up to the concurrency limit. āœ… Solution: ```javascript class AsyncQueue { constructor(concurrency) { this.concurrency = concurrency; this.running = 0; this.queue = []; } add(task) { return new Promise((resolve, reject) => { this.queue.push({ task, resolve, reject }); this.process(); }); } process() { while (this.running < this.concurrency && this.queue.length > 0) { const { task, resolve, reject } = this.queue.shift(); this.running++; Promise.resolve(task()).then(resolve).catch(reject).finally(() => { this.running--; this.process(); }); } } } ```

Async Queue (Concurrency Limiter)

Hard
Implement an `AsyncQueue` with a concurrency limit. `add(task)` queues tasks. No more than `concurrency` tasks run simultaneously.
Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
"function"