Skip to content

Instantly share code, notes, and snippets.

@bitifet
Created October 24, 2015 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitifet/f6914cb51bd1f22cfd85 to your computer and use it in GitHub Desktop.
Save bitifet/f6914cb51bd1f22cfd85 to your computer and use it in GitHub Desktop.
Asynchronous stack (LIFO)
"use strict";
var stack = (function(){
function _stack(){
this.stack = [];
this.queue = [];
};
_stack.prototype.push = function stack_push(data){
var me = this;
if (me.queue.length) {
me.queue.shift()(data);
} else {
me.stack.push(data);
}
};
_stack.prototype.pop = function stack_pop(){
var me = this;
if (me.stack.length) {
return Promise.resolve(me.stack.pop());
} else {
return new Promise(function(resolve, reject){
me.queue.push(function(data){
resolve(data);
});
});
};
};
return _stack;
})();
// Example:
// var s = new stack();
// s.push("hello");
// s.pop().then(function(data){console.log(data)});
// s.pop().then(function(data){console.log(data)});
// s.push("world");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment