Creating a Queue in Javascript


Though Arrays in JavaScript provide all the functionality of a Queue, let us implement our own Queue class. Our class will have the following functions −

  •  enqueue(element): Function to add an element in the queue.
  •  dequeue(): Function that removes an element from the queue.
  •  peek(): Returns the element from the front of the queue.
  •  isFull(): Checks if we reached the element limit on the queue.
  •  isEmpty(): checks if the queue is empty.
  •  clear(): Remove all elements.
  •  display(): display all contents of the array

Let's start by defining a simple class with a constructor that takes the max size of the queue and a helper function that'll help us when we implement the other functions for this class. As we implemented stacks, we'll implement queues using Arrays as well.

Example

class Queue {
   constructor(maxSize) {
      // Set default max size if not provided
      if (isNaN(maxSize)) {
         maxSize = 10;
       }
      this.maxSize = maxSize;
      // Init an array that'll contain the queue values.
      this.container = [];
   }
   // Helper function to display all values while developing
   display() {
      console.log(this.container);
   }
   // Checks if queue is empty
   isEmpty(){
      return this.container.length === 0;
   }
   // checks if queue is full
   isFull() {
      return this.container.length >= this.maxSize;
   }
}

We have also defined 2 more functions, isFull and isEmpty to check if the queue is full or empty.

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 the size of the container is 0.

These will be helpful when we define other operations. The functions we define from this point onwards will all go inside the Queue class.

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 15-Jun-2020

547 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements