这是Queue类的完整实现-
class Queue {
constructor(maxSize) {
//设置默认的最大大小(如果未提供)
if (isNaN(maxSize)) {
maxSize = 10;
}
this.maxSize = maxSize;
//初始化一个包含队列值的数组。
this.container = [];
}
//帮助程序功能在开发时显示所有值
display() {
console.log(this.container);
}
//检查队列是否为空
isEmpty() {
return this.container.length === 0;
}
//检查队列是否已满
isFull() {
return this.container.length >= this.maxSize;
}
enqueue(element) {
//检查队列是否已满
if (this.isFull()) {
console.log("队列溢出!"); return;
}
//由于我们要添加元素以结束,因此我们将其推送。
this.container.push(element);
}
dequeue() {
//检查是否为空
if (this.isEmpty()) {
console.log("队列下溢!");
return;
}
return this.container.shift();
}
peek() {
if (this.isEmpty()) {
console.log("队列下溢!");
return;
}
return this.container[0];
}
clear() {
this.container = [];
}
}