Created
March 19, 2021 11:55
-
-
Save NicholasMurray/0011ca2f2ba99994d93a4c5e2d3832d0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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