Peeking elements from a Stack in Javascript

JavascriptWeb DevelopmentFront End Technology

Consider a simple stack class in Javascript. 

Example

class Stack {
   constructor(maxSize) {
      // Set default max size if not provided
      if (isNaN(maxSize)) {
         maxSize = 10;
      }
      this.maxSize = maxSize; // Init an array that'll contain the stack values.
      this.container = [];
   }

   // A method just to see the contents while we develop this class
   display() {
      console.log(this.container);
   }

   // Checking if the array is empty
   isEmpty() {
      return this.container.length === 0;
   }
   
   // Check if array is full
   isFull() {
      return this.container.length >= maxSize;
   }

   push(element) {
      // Check if stack is full
      if (this.isFull()) {
         console.log("Stack Overflow!");
         return;
      }
      this.container.push(element);
   }

   pop() {
      // Check if empty
      if (this.isEmpty()) {
         console.log("Stack Underflow!");
         return;
      }
      this.container.pop();
   }
}

Here the isFull function just checks if the length of the container is equal to or more than maxSize and returns accordingly. The isEmpty function checks if a size of the container is 0. The Push and Pop functions are used to add and remove new elements from the stack respectively.

In this section, we are going to add PEEK operation in this class. Peeking a Stack means getting the top value of the array. So we can implement the peek function as follows −

peek() {
   if (isEmpty()) {
      console.log("Stack Underflow!");
      return;
   }
   return this.container[this.container.length - 1];
}

You can check if this function is working fine using −

Example

let s = new Stack(2);
s.peek();
s.push(10);
console.log(s.peek());

Output

This will give the output −

Stack Underflow!
10
raja
Published on 27-Jun-2018 06:58:47
Advertisements