Created
April 22, 2015 18:33
-
-
Save seemikehack/a037fa070e0cc57509ce to your computer and use it in GitHub Desktop.
Standard FIFO Queue, implemented with two stacks.
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
/** | |
* Standard FIFO Queue, implemented with two stacks. | |
* @typedef {Object} Queue | |
* @property {function} enqueue - add an item to the back of the queue | |
* @property {function} dequeue - remove an item from the front of the queue | |
* @property {function} isEmpty - check whether or not the queue is empty | |
*/ | |
/** | |
* Standard FIFO Queue, implemented with two stacks. | |
* @constructor | |
*/ | |
function Queue() { | |
// inbox | |
var en = []; | |
// outbox | |
var de = []; | |
/** | |
* Add an item to the back of the queue. | |
* @param {Object} o - the object to add | |
*/ | |
this.enqueue = function (o) { | |
en.push(o); | |
}; | |
/** | |
* Remove and item from the front of the queue. | |
* @returns {Object} the first item in the queue | |
*/ | |
this.dequeue = function () { | |
// if there's nothing in the outbox, flip the inbox | |
if (de.length === 0) | |
while (en.length !== 0) | |
de.push(en.pop()); | |
return de.pop(); | |
}; | |
/** | |
* Check whether or not the queue is empty. | |
* @returns {boolean} true if the queue is empty, false otherwise | |
*/ | |
this.isEmpty = function () { | |
return ((en.length === 0) && (de.length === 0)); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment