Last active
July 29, 2016 17:06
-
-
Save khaled0fares/4ffe7a9db1c4c71b1e361c2c636f0c71 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){ | |
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