-
-
Save emad-elsaid/eb5c84ee0ed7cbff451d0e5e7e5b6756 to your computer and use it in GitHub Desktop.
Stack implementation in JS using class and constructor
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' | |
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