Skip to content

Instantly share code, notes, and snippets.

@emad-elsaid
Forked from khaled0fares/stack.js
Last active July 29, 2016 17:14
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 emad-elsaid/eb5c84ee0ed7cbff451d0e5e7e5b6756 to your computer and use it in GitHub Desktop.
Save emad-elsaid/eb5c84ee0ed7cbff451d0e5e7e5b6756 to your computer and use it in GitHub Desktop.
Stack implementation in JS using class and constructor
'use strict'
let Stack = function(max){
if(typeof max != 'number' || max == NaN){
throw new Error(max + ' should be a number');
}
var Store = [],
top = 0,
empty = function() { return top === 0; },
full = function(){ return top === max; },
push = function(ele){
if(!this.full()){
Store[top++] = ele;
}else{
throw new Error('Stack is overflow');
}
},
pop = function(){
if(!empty()){
Store.splice(top-- - 1, 1);
}else{
throw new Error('Stack is empty, there is no element to be popped');
}
},
clear = function(){
Store = [];
top = 0;
},
peek = function(){
if(!empty()){
return Store[top -1 ];
}
throw new Error('Stack is empty, there is no element to be peeked');
},
toString = function(){
let i = 0;
if(!empty()){
for(i; i < top; i++){
console.log(Store[i]);
}
}
};
return {
empty: empty,
full: full,
push: push,
pop: pop,
clear: clear,
peek: peek,
toString: toString
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment