DEV Community

Saravana Kumar Putta Selvaraj
Saravana Kumar Putta Selvaraj

Posted on

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 that we are going to implement 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;  
 }
}
Enter fullscreen mode Exit fullscreen mode

push

class Stack {
  /* Initialization */
  constructor() {
    this.storage = {};
    this.stackLength = 0;
  }

  /* Add item to the stack */
  push(item) {
    this.storage[this.stackLength] = item;
    this.stackLength++;
  }
}
Enter fullscreen mode Exit fullscreen mode

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!"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

getStackSize

class Stack {
  /* Initialization */
  constructor() {
    this.storage = {};
    this.stackLength = 0;
  }

  /* To get the stack size */
  getStackSize() {
    return this.stackLength;
  }
}
Enter fullscreen mode Exit fullscreen mode

Complete Code

Please find the complete gits code here

Top comments (0)