Skip to content

Instantly share code, notes, and snippets.

@khaled0fares
Last active July 29, 2016 17:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save khaled0fares/4ffe7a9db1c4c71b1e361c2c636f0c71 to your computer and use it in GitHub Desktop.
Save khaled0fares/4ffe7a9db1c4c71b1e361c2c636f0c71 to your computer and use it in GitHub Desktop.
Stack implementation in JS using class and constructor
'use strict'
let Stack = function(max){
this.Store = [];
this.top = 0;
if(typeof max == 'number' && max != NaN){
this.max = max
}else{
throw new Error(max + ' should be a number');
}
}
Stack.prototype.empty = function() { return this.top === 0 }
Stack.prototype.full = function(){ return this.top === this.max}
Stack.prototype.push = function(ele){
if(!this.full()){
this.Store[this.top++] = ele;
}else{
throw new Error('Stack is overflow');
}
}
Stack.prototype.pop = function(){
if(!this.empty()){
this.Store.splice(this.top-- - 1, 1)
}else{
throw new Error('Stack is empty, there is no element to be popped');
}
}
Stack.prototype.clear = function(){
this.Store = [], this.top = 0;
}
//Get the top element of the stack
Stack.prototype.peek = function(){
if(!this.empty()){
return this.Store[this.top -1 ];
}
throw new Error('Stack is empty, there is no element to be peeked');
}
Stack.prototype.toString = function(){
let i = 0;
if(!this.empty()){
for(i; i < this.top; i++){
console.log(this.Store[i]);
}
}
}
//============ Using class definition ===============
class Stack{
constructor(max){
this.Store = [];
this.top = 0;
if(typeof max == 'number' && max != NaN){
this.max = max
}else{
throw new Error(`${max} should be a number`);
}
}
empty() { return this.top === 0 }
full(){ return this.top === this.max}
push(ele){
if(!this.full()){
this.Store[this.top++] = ele;
}else{
throw new Error('Stack is overflow');
}
}
pop(){
if(!this.empty()){
this.Store.splice(this.top-- - 1, 1)
}else{
throw new Error('Stack is empty, there is no element to be popped');
}
}
clear(){
this.Store = [], this.top = 0;
}
//Get the top element of the stack
peek(){
if(!this.empty()){
return this.Store[this.top -1 ];
}
throw new Error('Stack is empty, there is no element to be peeked');
}
toString(){
let i = 0;
if(!this.empty()){
for(i; i < this.top; i++){
console.log(this.Store[i]);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment