loading...

JS:DS - Stack Data Structure in JavaScript

saravanakumarputta profile image Saravana Kumar Putta Selvaraj ・1 min read

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;  
 }
}

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

Please find the complete gits code here

Posted on Jun 12 by:

saravanakumarputta profile

Saravana Kumar Putta Selvaraj

@saravanakumarputta

Self-taught Full Stack Javascript developer. Newbie @ blogging and Platform Engineer @ ZohoDesk

Discussion

markdown guide