The PriorityQueue Class in Javascript

A Priority Queue is a data structure where each element has an associated priority. Elements with higher priority are served before elements with lower priority. In JavaScript, we can implement this using a class-based approach.

Complete PriorityQueue Implementation

Here's a complete implementation of the PriorityQueue class with all essential methods:

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;
   }
   
   enqueue(data, priority) {
      // Check if Queue is full
      if (this.isFull()) {
         console.log("Queue Overflow!");
         return;
      }
      let currElem = new this.Element(data, priority);
      let addedFlag = false;
      
      // Insert element based on priority (lower number = higher priority)
      for (let i = 0; i < this.container.length; i++) {
         if (currElem.priority < this.container[i].priority) {
            this.container.splice(i, 0, currElem);
            addedFlag = true; 
            break;
         }
      }
      if (!addedFlag) {
         this.container.push(currElem);
      }
   }
   
   dequeue() {
      // Check if empty
      if (this.isEmpty()) {
         console.log("Queue Underflow!");
         return;
      }
      return this.container.shift();
   }
   
   peek() {
      if (this.isEmpty()) {
         console.log("Queue Underflow!");
         return;
      }
      return this.container[0];
   }
   
   clear() {
      this.container = [];
   }
}

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

Usage Example

Let's demonstrate how to use the PriorityQueue with different priority levels:

// Create a priority queue with max size of 5
let pq = new PriorityQueue(5);

// Add elements with different priorities (lower number = higher priority)
pq.enqueue("Emergency Task", 1);
pq.enqueue("Normal Task", 3);
pq.enqueue("High Priority Task", 2);
pq.enqueue("Low Priority Task", 4);

console.log("Priority Queue contents:");
pq.display();

console.log("Peek at highest priority:", pq.peek());

console.log("Processing tasks by priority:");
while (!pq.isEmpty()) {
   let task = pq.dequeue();
   console.log(`Processing: ${task.data} (Priority: ${task.priority})`);
}
Priority Queue contents:
[
  { data: 'Emergency Task', priority: 1 },
  { data: 'High Priority Task', priority: 2 },
  { data: 'Normal Task', priority: 3 },
  { data: 'Low Priority Task', priority: 4 }
]
Peek at highest priority: { data: 'Emergency Task', priority: 1 }
Processing tasks by priority:
Processing: Emergency Task (Priority: 1)
Processing: High Priority Task (Priority: 2)
Processing: Normal Task (Priority: 3)
Processing: Low Priority Task (Priority: 4)

Key Features

Method Purpose Time Complexity
enqueue(data, priority) Add element with priority O(n)
dequeue() Remove highest priority element O(1)
peek() View highest priority element O(1)
isEmpty() Check if queue is empty O(1)

Priority System

In this implementation, lower numbers represent higher priority. For example, priority 1 is processed before priority 3. Elements with the same priority are processed in the order they were added (FIFO).

Conclusion

The PriorityQueue class provides an efficient way to manage tasks or data based on priority levels. It's particularly useful in scenarios like task scheduling, emergency systems, or algorithm implementations where order matters based on importance rather than insertion time.

Updated on: 2026-03-15T23:18:59+05:30

271 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements