用JS实现队列、循环队列与任务调度
请用JavaScript实现一个普通队列和循环队列,并说明队列在JS任务调度中的应用。
回答
古法程序员
class Queue {
#items = {};
#head = 0;
#tail = 0;
enqueue(item) { this.#items[this.#tail++] = item; }
dequeue() {
if (this.isEmpty()) return null;
const item = this.#items[this.#head];
delete this.#items[this.#head++];
return item;
}
isEmpty() { return this.#head === this.#tail; }
get size() { return this.#tail - this.#head; }
}
// 循环队列(固定大小)
class CircularQueue {
constructor(k) {
this.items = new Array(k);
this.capacity = k;
this.head = 0;
this.tail = 0;
this.count = 0;
}
enqueue(item) {
if (this.count === this.capacity) return false;
this.items[this.tail] = item;
this.tail = (this.tail + 1) % this.capacity;
this.count++;
return true;
}
dequeue() {
if (this.count === 0) return null;
const item = this.items[this.head];
this.head = (this.head + 1) % this.capacity;
this.count--;
return item;
}
}
JS队列应用:JS事件循环中的任务队列(macroTaskQueue/microTaskQueue)、异步请求并发控制(p-limit)、BFS遍历、消息队列、日志缓冲。