Implement Priority Queue in Javascript

April 13, 2021Swapnil Patil

What is Queue?

Most of the engineers are aware of this, so feel free to skip. Queue is data structure which follow rule - First In First Out (FIFO)

Below is the minimal implementation of queue in javascript.

let queue = []
queue.push(1)
queue.push(2)
queue.shift() // output 1
queue.shift() // output 2

What is Priority Queue?

Simple queue does not account for weightage or importance for object we are storing. Priority queue will serve you item with highest priority at any given time.

Priority Queue is Binary Max Heap with rule - It is a tree where parent is always greater than children.

Always remember, we need to visualise Priority Queue as Binary Max Heap instead of implementation of queue.

Benefits

There are enormous amount applications based on Priority Queue.

  • In hospitals we can use priority queue based on severity of patient
  • Load balancing can be implemented based on action users are doing
  • Dijkstra’s algorithm used priority queue

Implementation

We are going to implement enqueue and dequeue methods. We will use array to store the values. Do remember below important formulas below -

  • find parent index of current node - const parentIndex = Math.floor(index - 1 / 2)

  • find left children index of current node - const leftIndex = (2 * index) + 1

  • Get right children index of current node - const rightIndex = (2 * index) + 2

enqueue - Insert in queue

dequeue - remove from queue

Full Code Github or Try Below


I work as a Software Engineer in Microsoft. I have Experience in Enterprise Web and Hybrid Mobile Applications. I am a techie and I love making cool products.