It won't work in all scenarios. Here are 2 issues:
- if
this.vals.length === 0 && this.indexOfFirst < 0
then push()
and pop()
won't behave as desired
- if
this.indexOfFirst
drops below Number.MIN_SAFE_INTEGER
then unshift()
will fail to add values to the queue
To fix the first issue you can use a Map
instead of an Array
along with a indexOfLast
like you are already handling indexOfFirst
:
class Queue {
indexedVals = new Map();
indexOfFirst = 0;
indexOfLast = -1;
constructor(vals) {
if (vals) for (const val of vals) this.push(val);
}
shift() {
if (this.indexOfFirst > this.indexOfLast) return;
const val = this.indexedVals.get(this.indexOfFirst);
this.indexedVals.delete(this.indexOfFirst++);
return val;
}
unshift(val) {
this.indexedVals.set(--this.indexOfFirst, val);
}
pop() {
if (this.indexOfLast < this.indexOfFirst) return;
const val = this.indexedVals.get(this.indexOfLast);
this.indexedVals.delete(this.indexOfLast--);
return val;
}
push(val) {
this.indexedVals.set(++this.indexOfLast, val);
}
}
To fix the second issue you can use BigInt
instead of Number
or you can implement a doubly-linked list where each node stores a value along with a pointer to the next and previous nodes (thereby avoiding any numeric limitations).