Skip to content

Instantly share code, notes, and snippets.

@saravanakumarputta
Last active June 12, 2020 15: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 saravanakumarputta/deb51dc418ab9c7aff47498f2c5941e0 to your computer and use it in GitHub Desktop.
Save saravanakumarputta/deb51dc418ab9c7aff47498f2c5941e0 to your computer and use it in GitHub Desktop.
Stack DS:JS blog
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