Skip to content

Instantly share code, notes, and snippets.

@NicholasMurray
Created March 19, 2021 11:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NicholasMurray/0011ca2f2ba99994d93a4c5e2d3832d0 to your computer and use it in GitHub Desktop.
Save NicholasMurray/0011ca2f2ba99994d93a4c5e2d3832d0 to your computer and use it in GitHub Desktop.
class Queue {
constructor() {
this.items = {};
this.headIndex = 0;
this.tailIndex = 0;
}
enqueue(item) {
this.items[this.tailIndex] = item;
this.tailIndex++;
}
dequeue() {
const item = this.items[this.headIndex];
delete this.items[this.headIndex];
this.headIndex++;
return item;
}
peek() {
return this.items[this.headIndex];
}
get length() {
return this.tailIndex - this.headIndex;
}
}
const queue = new Queue();
queue.enqueue(7);
queue.enqueue(2);
queue.enqueue(6);
queue.enqueue(4);
queue.dequeue(); // => 7
queue.peek(); // => 2
queue.length; // => 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment