JS:DS — Stack Data Structure in JavaScript
In this write-up, we are going to see how the stack data structure can be implemented in Javascript.
What is a Stack?
The stack is a data structure to store the data in the order of insertion where the item gets inserted at the last into the stack will be the first one to be removed.
In shorter terms Last In First Out(LIFO).
How are we going to implement it?
The following are the methods and variables we are going to have in Stack DS.
initialize — Initialize the storage and stack size
push — push data to the stack
pop — Remove the last pushed item from the stack
getStackSize — Get the current stack size
initialize
class Stack {
/* Initialization */
constructor() {
this.storage = {};
this.stackLength = 0;
}
}
push
class Stack {
/* Initialization */
constructor() {
this.storage = {};
this.stackLength = 0;
}
/* Add item to the stack */
push(item) {
this.storage[this.stackLength] = item;
this.stackLength++;
}
}
pop
class Stack {
/* Initialization */
constructor() {
this.storage = {};
this.stackLength = 0;
}
/* 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!"
}
}
}
getStackSize
class Stack {
/* Initialization */
constructor() {
this.storage = {};
this.stackLength = 0;
}
/* To get the stack size */
getStackSize() {
return this.stackLength;
}
}
Complete Code
We can also add additional features like default stack size, get the last item, etc.,
This article is made with ❤️and special thanks to the dev community from where I learned this.