Priority queue in javascript

Ujjwal Gupta
2 min readJan 13, 2021

Priority queue are special type of queue where items are stored with their priority. So that element can be extracted based on their priority.

A simple example will be a ticketing system of any event. Where we first want to allot ticket to old people, so their priority will be high for old people.

or for same system let’s say its Christmas time & we want to allot ticket to children first. So we will allot ticket to people who has lowest priority.

Now, lets write program for priority Queue —

class Item {
constructor(value, priority) {
this.value = value;
this.priority = priority;
}
}
class PriorityQueue { constructor() {
this.items = [];
}
add(item, priority) {
let isAdded = false;
const newQueueItem = new Item(item, priority);
this.items.every((item, index) => {
if (item.priority > newQueueItem.priority) {
this.items.splice(index, 0, newQueueItem);
isAdded = true;
return false;
}
return true;
})
if (!isAdded) {
this.items.push(newQueueItem);
}
}
}const queue = new PriorityQueue();
queue.add(5, 1);
queue.add(10, 0);
queue.add(20, 2);
console.log(JSON.stringify(queue.items));

So fundamental is we store the element in an array in sorted order. Element with lowest priority first and highest priority last.

Now, how to delete element. Delete element is simple, element with lowest priority is deleted first, so we will have to use array method to remove first element. I will leave that upto you to implement & learn :).

Hope this is helpful. Feel free to ask question and discuss. Don’t forget to clap & share with your friends.

In case you want to connect with me. Here is my portfolio — https://ujjwalguptaofficial.github.io/

--

--

Ujjwal Gupta

Frontend lead Polygon | Creator of jsstore, mahaljs | sqlweb, fortjs | opensource creator | we3, blockchain, solidity | javascript