Created
October 24, 2015 09:40
-
-
Save bitifet/f6914cb51bd1f22cfd85 to your computer and use it in GitHub Desktop.
Asynchronous stack (LIFO)
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
"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