Sequence NODE_237
Medium

Implement a Simple Task Queue

Node.js
Technical Specification

Implement a simple in-memory queue that processes async tasks one by one.

Input/Output Samples
Input:addTask(async () => wait 1s)
Output:Tasks run sequentially
Optimal Logic Path
class TaskQueue {
  constructor() {
    this.queue = [];
    this.running = false;
  }
  add(task) {
    this.queue.push(task);
    this.run();
  }
  async run() {
    if (this.running) return;
    this.running = true;
    while (this.queue.length) {
      const fn = this.queue.shift();
      await fn();
    }
    this.running = false;
  }
}

module.exports = TaskQueue;
Architectural Deep-Dive
We serialize async tasks by awaiting each one in sequence in a loop.