Last active
June 12, 2020 15:14
-
-
Save saravanakumarputta/deb51dc418ab9c7aff47498f2c5941e0 to your computer and use it in GitHub Desktop.
Stack DS:JS blog
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
class Stack { | |
/* Initialization */ | |
constructor() { | |
this.storage = {}; | |
this.stackLength = 0; | |
} | |
/* To get the stack size */ | |
getStackSize() { | |
return this.stackLength; | |
} | |
/* Add item to the stack */ | |
push(item) { | |
this.storage[this.stackLength] = item; | |
this.stackLength++; | |
} | |
/* Remove Item from the stack with below conditions | |
1. Get the last index | |
2. check the stack is non-empty | |
3. remove the item from the storage | |
*/ | |
pop() { | |
let endIndex = this.stackLength - 1; | |
if (endIndex >= 0) { | |
delete this.storage[endIndex] | |
this.stackLength--; | |
} else { | |
throw "Stack is Empty, cannot pop!" | |
} | |
} | |
} | |
/* Initialize new Stack */ | |
let s1 = new Stack(); | |
/* Access stack methods as | |
s1.push(item), | |
s1.pop() | |
s1.getStackLength() | |
*/ | |
console.log(s1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment