这里写自定义目录标题
Js 队列简单实现
队列简单实现,Queue有两个工具函数,用来判断越界,与增加容量。
class Collection {
DEFAULT_CAPACITY = 10;
}
export class Queue extends Collection {
constructor(capacity) {
super();
capacity ||= this.DEFAULT_CAPACITY;
this._elements = new Array(capacity);
this._capacity = capacity;
this._size = 0;
}
isExcessRange(index) {
return index < 0 || index >= this._size;
}
ensureCapacity(capacity) {
if (this._capacity < capacity) {
this._capacity = this._capacity + (this._capacity >> 1);
const newElements = new Array(this._capacity);
for (let i = 0; i < this._size; i++) {
newElements[i] = this._elements[i];
}
this._elements = newElements;
}
}
enqueue(element) {
this.ensureCapacity(this._size + 1);
this._elements[this._size] = element;
this._size++;
}
dequeue() {
const dequeueElement = this._elements[0];
if (this._size > 0) {
const newElements = new Array(this._capacity);
for (let i = 0; i < this._size; i++) {
newElements[i] = this._elements[i + 1];
}
this._elements = newElements;
this._size--;
}
return dequeueElement;
}
size() {
return this._size;
}
}
const queue1 = new Queue(2);
console.log(queue1);