Creating a Priority Queue using Javascript


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. We'll also have to define another structure as part of the PriorityQueue class prototype that'll have the priority and data about each node. As we implemented stacks, we'll implement Priority Queue using Arrays as well. 

Example

class PriorityQueue {
   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;
   }
}
// Create an inner class that we'll use to create new nodes in the queue
// Each element has some data and a priority
PriorityQueue.prototype.Element = class {
   constructor (data, priority) {
      this.data = data; this.priority = priority;
   }
}

We have also defined 2 more functions, isFull and isEmpty to check if the stack 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 into the PriorityQueue class.

Updated on: 15-Jun-2020

376 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements