Implementation of Priority Queue in Javascript

Priority Queue is an extension of Queue having some properties as follows:

  1. Each element of the priority queue has an property associated with it.
  2. Elements are added to the queue as per the priority.
  3. Lowest priority elements are removed first.

We can design a priority queue using two approaches in the first case we can add the queue element at the end of the queue and we can remove the elements of the queue depending on the priority. In the second case we can add elements to the queue according to the priority and remove them from the front of the queeue. In this article we would use the second approach to implement a Priority Queue.
Note: Assuming a Priority queue can grow dynamically we are not considering the overflow condition.
Let’s see an example of a priority queue class:
Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// User defined class
// to store element and its priority
class QElement {
    constructor(element, priority)
    {
        this.element = element;
        this.priority = priority;
    }
}
  
// PriorityQueue class
class PriorityQueue {
  
    // An array is used to implement priority
    constructor()
    {
        this.items = [];
    }
  
    // functions to be implemented
    // enqueue(item, priority)
    // dequeue()
    // front()
    // isEmpty()
    // printPQueue()
}

chevron_right


As you can see in the example above we have defined skeleton of PriorityQueue class. We have use an user defined class QElement having two property element and priority. We have used an array in PriorityQueue class to implement priority queue, this array is a container of QElement.

  1. enqueue() – adds an element to the queue according to its priority.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // enqueue function to add element
    // to the queue as per priority
    enqueue(element, priority)
    {
        // creating object from queue element
        var qElement = new QElement(element, priority);
        var contain = false;
      
        // iterating through the entire
        // item array to add element at the
        // correct location of the Queue
        for (var i = 0; i < this.items.length; i++) {
            if (this.items[i].priority > qElement.priority) {
                // Once the correct location is found it is
                // enqueued
                this.items.splice(i, 0, qElement);
                contain = true;
                break;
            }
        }
      
        // if the element have the highest priority
        // it is added at the end of the queue
        if (!contain) {
            this.items.push(qElement);
        }
    }

    chevron_right

    
    

    In this method we create a qElement have property element and priority. Then we iterate over the queue to find the correct location of the qElement according to its priority and add it.

  2. dequeue() – Removes an element from the priority queue
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // dequeue method to remove
    // element from the queue
    dequeue()
    {
        // return the dequeued element
        // and remove it.
        // if the queue is empty
        // returns Underflow
        if (this.isEmpty())
            return "Underflow";
        return this.items.shift();
    }

    chevron_right

    
    

    This function removes an element from the front of a queue as the highest priority element is stored at the front of the priority queue. We have used shift method of an array to remove an element from the queue.

  3. front() – returns the front element of the Priority queue
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // front function
    front()
    {
        // returns the highest priority element
        // in the Priority queue without removing it.
        if (this.isEmpty())
            return "No elements in Queue";
        return this.items[0];
    }

    chevron_right

    
    

    This function returns the front element of the Priority queue. We simply return the 0th element of an array to get the front of a Priority queue.

  4. rear() – returns the last element of the Priority queue
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // rear function
    rear()
    {
        // returns the lowest priorty
        // element of the queue
        if (this.isEmpty())
            return "No elements in Queue";
        return this.items[this.items.length - 1];
    }

    chevron_right

    
    

    This functions return the last element of the queue or lowest priority element.

Helper Methods:
Let’s declare some helper method which is quite useful while working with the Priority queue queue.

  1. isEmpty() – Returns true if the Priority queue is empty
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // isEmpty function
    isEmpty()
    {
        // return true if the queue is empty.
        return this.items.length == 0;
    }

    chevron_right

    
    

    We have used the length property of an array to get the length and if its 0 then priority queue is empty.



  2. printPQueue – It prints the element of the queue as per the priority starting from highest to lowest

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // printQueue function
    // prints all the element of the queue
    printPQueue()
    {
        var str = "";
        for (var i = 0; i < this.items.length; i++)
            str += this.items[i].element + " ";
        return str;
    }

    chevron_right

    
    

    In this method we concatenate the element property of each priority queue item into an string.

Note :- Here we consider ” 1 ” as the highest priority element, you can modify this as per the requirement.
Implementation
Now Let use this Priority Queue class and its different method described above

filter_none

edit
close

play_arrow

link
brightness_4
code

// creating object for queue classs
var priorityQueue = new PriorityQueue();
  
// testing isEmpty and front on an empty queue
// return true
console.log(priorityQueue.isEmpty());
  
// returns "No elements in Queue"
console.log(priorityQueue.front());
  
// adding elements to the queue
priorityQueue.enqueue("Sumit", 2);
priorityQueue.enqueue("Gourav", 1);
priorityQueue.enqueue("Piyush", 1);
priorityQueue.enqueue("Sunny", 2);
priorityQueue.enqueue("Sheru", 3);
  
// prints [Gourav Piyush Sumit Sunny Sheru]
console.log(priorityQueue.printPQueue());
  
// prints Gourav
console.log(priorityQueue.front().element);
  
// pritns Sheru
console.log(priorityQueue.rear().element);
  
// removes Gouurav
// priorityQueue contains
// [Piyush Sumit Sunny Sheru]
console.log(priorityQueue.dequeue().element);
  
// Adding another element to the queue
priorityQueue.enqueue("Sunil", 2);
  
// prints [Piyush Sumit Sunny Sunil Sheru]
console.log(priorityQueue.printPQueue());

chevron_right


This article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.