Skip to content

Instantly share code, notes, and snippets.

@mayashavin
Last active January 10, 2018 13:54
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 mayashavin/3f2507732d457447c66da5ffe8d2c50f to your computer and use it in GitHub Desktop.
Save mayashavin/3f2507732d457447c66da5ffe8d2c50f to your computer and use it in GitHub Desktop.
Data Structures - Stack in JS without using Array - Full Demo: https://jsfiddle.net/dpnminh/g1xy22cz/
function Stack(){
var stack = {};
var stackSize = 0;
return {
push: function(item){
stack[stackSize] = item;
stackSize++;
},
pop: function(){
if (this.isEmpty()){ return undefined;}
stackSize--;
var item = stack[stackSize];
delete stack[stackSize];
return item;
},
peek: function(){
if (this.isEmpty()){
return undefined;
}
return stack[stackSize - 1];
},
stackEmpty: function(){
while (!this.isEmpty()){
this.pop();
}
},
isEmpty: function(){
return stackSize === 0;
},
size: function(){
return stackSize;
},
print: function(){
var result = [];
for (var key in stack){
result.unshift(stack[key]);
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment