Clearing the elements of a Stack in Javascript

Web DevelopmentFront End TechnologyJavascript

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();
   }
   peek() {
      if (isEmpty()) {
         console.log("Stack Underflow!");
         return;
      }
      return this.container[this.container.length - 1];
   }
}

Here the isFull function just checks if the length of a 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 CLEAR operation in this class. We can clear the contents just by reassigning the container element to an empty array. For example,

Example

clear() {
   this.container = [];
}

You can check if this function is working fine using −

Example

let s = new Stack(2);
s.push(10);
s.push(20);
s.display();
s.clear();
s.display();

Output

This will give the output −

[10, 20]
[]
raja
Published on 27-Jun-2018 10:33:25
Advertisements