Creating a Priority Queue using Javascript

A priority queue is a data structure where each element has a priority. Elements are removed based on their priority rather than insertion order. Here's how to implement one using JavaScript arrays.

Priority Queue Structure

Our priority queue class will include these essential methods:

  • enqueue(element, priority): Add an element with a specific priority
  • dequeue(): Remove and return the highest priority element
  • peek(): Return the highest priority element without removing it
  • isEmpty(): Check if the queue is empty
  • isFull(): Check if the queue has reached capacity
  • display(): Show all queue contents

Basic Implementation

Let's create the foundation with a constructor and helper methods:

class PriorityQueue {
    constructor(maxSize) {
        // Set default max size if not provided
        if (isNaN(maxSize)) {
            maxSize = 10;
        }
        this.maxSize = maxSize;
        // Array to contain queue elements
        this.container = [];
    }
    
    // Helper function to display all values
    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;
    }
}

// Inner class for queue elements
PriorityQueue.prototype.Element = class {
    constructor(data, priority) {
        this.data = data;
        this.priority = priority;
    }
}

// Test the basic structure
let pq = new PriorityQueue(5);
console.log("Is empty:", pq.isEmpty());
console.log("Is full:", pq.isFull());
Is empty: true
Is full: false

Adding Core Operations

Now let's implement the enqueue and dequeue operations. In a priority queue, lower numbers typically represent higher priority:

class PriorityQueue {
    constructor(maxSize) {
        if (isNaN(maxSize)) {
            maxSize = 10;
        }
        this.maxSize = maxSize;
        this.container = [];
    }
    
    // Add element with priority
    enqueue(data, priority) {
        if (this.isFull()) {
            console.log("Queue is full!");
            return false;
        }
        
        const element = new this.constructor.prototype.Element(data, priority);
        
        // Insert element in correct position based on priority
        let inserted = false;
        for (let i = 0; i < this.container.length; i++) {
            if (element.priority < this.container[i].priority) {
                this.container.splice(i, 0, element);
                inserted = true;
                break;
            }
        }
        
        // If not inserted, add to end
        if (!inserted) {
            this.container.push(element);
        }
        return true;
    }
    
    // Remove highest priority element
    dequeue() {
        if (this.isEmpty()) {
            console.log("Queue is empty!");
            return null;
        }
        return this.container.shift();
    }
    
    // Peek at highest priority element
    peek() {
        if (this.isEmpty()) {
            return null;
        }
        return this.container[0];
    }
    
    isEmpty() {
        return this.container.length === 0;
    }
    
    isFull() {
        return this.container.length >= this.maxSize;
    }
    
    display() {
        console.log(this.container.map(el => `${el.data}(${el.priority})`));
    }
}

PriorityQueue.prototype.Element = class {
    constructor(data, priority) {
        this.data = data;
        this.priority = priority;
    }
}

// Test the priority queue
let pq = new PriorityQueue(5);

pq.enqueue("Low priority task", 5);
pq.enqueue("High priority task", 1);
pq.enqueue("Medium priority task", 3);

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

console.log("Peek:", pq.peek().data);
console.log("Dequeue:", pq.dequeue().data);
console.log("After dequeue:");
pq.display();
Queue contents:
[ 'High priority task(1)', 'Medium priority task(3)', 'Low priority task(5)' ]
Peek: High priority task
Dequeue: High priority task
After dequeue:
[ 'Medium priority task(3)', 'Low priority task(5)' ]

Complete Priority Queue Example

Here's a practical example showing how the priority queue maintains order:

class PriorityQueue {
    constructor(maxSize = 10) {
        this.maxSize = maxSize;
        this.container = [];
    }
    
    enqueue(data, priority) {
        if (this.isFull()) {
            return false;
        }
        
        const element = { data, priority };
        let inserted = false;
        
        for (let i = 0; i < this.container.length; i++) {
            if (priority < this.container[i].priority) {
                this.container.splice(i, 0, element);
                inserted = true;
                break;
            }
        }
        
        if (!inserted) {
            this.container.push(element);
        }
        return true;
    }
    
    dequeue() {
        return this.isEmpty() ? null : this.container.shift();
    }
    
    peek() {
        return this.isEmpty() ? null : this.container[0];
    }
    
    isEmpty() {
        return this.container.length === 0;
    }
    
    isFull() {
        return this.container.length >= this.maxSize;
    }
    
    clear() {
        this.container = [];
    }
    
    size() {
        return this.container.length;
    }
}

// Hospital emergency room example
let emergencyQueue = new PriorityQueue(10);

emergencyQueue.enqueue("Broken arm", 3);
emergencyQueue.enqueue("Heart attack", 1);
emergencyQueue.enqueue("Headache", 5);
emergencyQueue.enqueue("Severe bleeding", 1);

console.log("Emergency queue processing:");
while (!emergencyQueue.isEmpty()) {
    let patient = emergencyQueue.dequeue();
    console.log(`Treating: ${patient.data} (Priority: ${patient.priority})`);
}
Emergency queue processing:
Treating: Heart attack (Priority: 1)
Treating: Severe bleeding (Priority: 1)
Treating: Broken arm (Priority: 3)
Treating: Headache (Priority: 5)

Key Features

  • Priority-based ordering: Elements are automatically sorted by priority
  • Efficient insertion: New elements are inserted in the correct position
  • Capacity management: Built-in size limits prevent overflow
  • Flexible priorities: Lower numbers represent higher priority

Conclusion

Priority queues are essential for task scheduling and resource management. This array-based implementation provides O(n) insertion but guarantees proper priority ordering for efficient processing.

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

570 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements