Priority Queue in ES6 JavaScript
I recently found myself trying to find a shortest path between two points in JavaScript. The approach I took was similar to Dijkstra's algorithm. A key component to the algorithm is the priority queue used to determine which edge should be evaluated next in the main loop.
In Python, the standard lib includes heapq but when I looked for something similar in JavaScript, I found a lot of overly complex solutions. In such cases, I usually just roll my own implementation.
class PriorityQueue {
constructor() {
this.data = [];
}
push(value, priority = 0) {
return this.data.push({
value: value,
priority: priority
});
}
pop() {
let index = 0;
let min = Infinity;
for (let i = 0; i < this.data.length; i++) {
let priority = this.data[i].priority;
if (Math.min(min, priority) === priority) {
min = priority;
index = i;
}
}
return this.data.splice(index, 1)[0].value;
}
size() {
return this.data.length;
}
}
Hopefully this is useful for someone else out there looking for the same thing. It's fairly straightforward to use. You can add arbitrary values using push(value, priority)
and when you pop()
, the item with the highest priority (lowest value) will be removed and returned.