Just for kicks, I created a version that doesn’t use shift
:
class Queue {
constructor(...items) {
this.items = items;
this.start = 0;
}
clear() {
this.items.length = 0;
}
clone() {
var newItems = this.items.slice(this.start);
return new Queue(...newItems);
}
contains(item) {
return this.items.includes(item);
}
peek() {
var item = null;
if (this.items.length > this.start) {
item = this.items[this.start];
}
return item;
}
dequeue() {
var removedItem = this.items[this.start];
this.start++;
return removedItem;
}
enqueue(item) {
this.items.push(item);
return item;
}
}
Usage of this should be the same as the earlier. In my cursory testing, As I mention below, it is slower than the shift
approach for some bizarre reason.
Cheers,
Kirupa