Skip to content

Instantly share code, notes, and snippets.

@Kreijstal
Created August 7, 2014 23:21
Show Gist options
  • Save Kreijstal/b6c72830a177ffbb9a91 to your computer and use it in GitHub Desktop.
Save Kreijstal/b6c72830a177ffbb9a91 to your computer and use it in GitHub Desktop.
function Queue(){
// initialise the queue and offset
this.queue = [];
this.offset = 0;
}
// Returns the length of the queue.
Queue.prototype.getLength = function(){
return (this.queue.length - offset);
}
// Returns true if the queue is empty, and false otherwise.
Queue.prototype.isEmpty = function(){
return (this.queue.length == 0);
}
/* Enqueues the specified item. The parameter is:
*
* item - the item to enqueue
*/
Queue.prototype.enqueue = function(item){
this.queue.push(item);
}
/* Dequeues an item and returns it. If the queue is empty, the value
* 'undefined' is returned.
*/
Queue.prototype.dequeue = function(){
// if the queue is empty, return immediately
if (this.queue.length == 0) return undefined;
// store the item at the front of the queue
var item = this.queue[this.offset];
// increment the offset and remove the free space if necessary
if (++ this.offset * 2 >= this.queue.length){
this.queue = this.queue.slice(this.offset);
this.offset = 0;
}
// return the dequeued item
return item;
}
/* Returns the item at the front of the queue (without dequeuing it). If the
* queue is empty then undefined is returned.
*/
Queue.prototype.peek = function(){
return (this.queue.length > 0 ? this.queue[this.offset] : undefined);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment