Skip to content

Instantly share code, notes, and snippets.

@sabique
Created October 14, 2020 18:59
Show Gist options
  • Save sabique/dc9666cfcf48dc1a477914f6901ca406 to your computer and use it in GitHub Desktop.
Save sabique/dc9666cfcf48dc1a477914f6901ca406 to your computer and use it in GitHub Desktop.
/** Class representing a Queue.
* @constructor
*/
class Queue {
constructor() {
this._storage = {};
this._length = 0;
this._headIndex = 0;
}
/*
* Enqueues a new value at the end of the queue
* @param {*} value the value to enqueue
*/
enqueue(value) {
if(value !== ''){
this._storage[this._headIndex + this._length] = value;
this._length++;
}
}
/*
* Dequeues the value from the beginning of the queue and returns it
* @return {*} the first and oldest value in the queue
*/
dequeue() {
if(!this.isEmpty()){
const value = this._storage[this._headIndex];
delete this._storage[this._headIndex];
this._length--;
this._headIndex++;
return value;
}
}
/*
* Returns the value at the beginning of the queue without removing it from the queue
* @return {*} the first and oldest value in the queue
*/
peek() {
if(!this.isEmpty()){
return this._storage[this._headIndex];
}
}
/*
* Returns true if queue is empty else false
*/
isEmpty(){
return this._length === 0;
}
}
let queue = new Queue();
queue.enqueue('zero');
queue.peek();
queue.dequeue();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment