Skip to content

Instantly share code, notes, and snippets.

@mitrakmt
Created September 19, 2016 03:42
Show Gist options
  • Save mitrakmt/6d2e76a9a177b02e464669030e1a6cd7 to your computer and use it in GitHub Desktop.
Save mitrakmt/6d2e76a9a177b02e464669030e1a6cd7 to your computer and use it in GitHub Desktop.
How to implement a Queue in JavaScript
// This Stack is written using the pseudoclassical pattern
// Creates the queue
var Queue = function() {
this.storage = {};
this.count = 0;
this.lowestCount = 0;
}
// Adds a value to the end of the chain
Queue.prototype.enqueue = function(value) {
// Check to see if value is defined
if (value) {
this.storage[this.count] = value;
this.count++;
}
}
// Removes a value from the beginning of the chain
Queue.prototype.dequeue = function() {
// Check to see if queue is empty
if (this.count - this.lowestCount === 0) {
return undefined;
}
var result = this.storage[this.lowestCount];
delete this.storage[this.lowestCount];
this.lowestCount++;
return result;
}
// Returns the length of the queue
Queue.prototype.size = function() {
return this.count - this.lowestCount;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment