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();
});
}
}
}
```