Table of Contents
About The Project
Javascript Priority Queue ( Min / Max Heap ).
| Peek | O(1) |
| Enqueue | O(logn) |
| Dequeue | O(logn) |
| Clear | O(1) |
(back to top)
Getting Started
Installation
npm i @practicaljs/priority-queue
Usage
Create a new priority queue class
const queue = new PriorityQueue<number>((a, b) => a - b);
To prioritize lower values use a-b, for higher values use b-a
example
const nums = [3, 5, 9, 4, 1, 6, 2, 7, 8];
const queue = new PriorityQueue<number>((a, b) => a - b);
const queue = new PriorityQueue<number>((a, b) => b - a);
The same can be done for objects
const foodLikes = [
{ name: 'sushi', rating: 4 },
{ name: 'chicken', rating: 4 },
{ name: 'beef', rating: 5 },
{ name: 'pork', rating: 1 }
];
const queue = new PriorityQueue<typeof foodLikes[0]>((a, b) => a.rating - b.rating);
const queue = new PriorityQueue<typeof foodLikes[0]>((a, b) => b.rating - a.rating);
You can also prioritize object by special logic, in this case the object you want to prioritize give it a lower value
const events = [
{ name: 'Dinner', time: 19 },
{ name: 'Special - House Music', time: 22 },
{ name: 'lunch', time: 12 },
{ name: 'breakfast', time: 7 },
{ name: 'Special - Live Music', time: 23 }
];
const queue = new PriorityQueue<typeof events[0]>((a, b) => {
const aRating = a.name.startsWith('Special') ? 0 : 2;
const bRating = b.name.startsWith('Special') ? 0 : 2;
return aRating - bRating;
});
You can also prioritize by secondary vaules
const events = [
{ name: 'Dinner', time: 19 },
{ name: 'Special - House Music', time: 22 },
{ name: 'lunch', time: 12 },
{ name: 'breakfast', time: 7 },
{ name: 'Special - Live Music', time: 23 }
];
const queue = new PriorityQueue<typeof events[0]>((a, b) => {
const aRating = a.name.startsWith('Special') ? 0 : 2;
const bRating = b.name.startsWith('Special') ? 0 : 2;
if (aRating == bRating) {
return a.time - b.time
}
return aRating - bRating;
});