A highly performant priority queue implementation using a Min Heap data structure.
npm install --save @datastructures-js/priority-queueconst PriorityQueue = require('@datastructures-js/priority-queue');import PriorityQueue from '@datastructures-js/priority-queue';const priorityQueue = new PriorityQueue();adds an element with a priority (number) to the queue. The smaller the number, the higher the priority.
| params | ||
|---|---|---|
| name | type | |
| element | object | |
| priority | number | |
| runtime |
|---|
| O(log(n)) |
priorityQueue.enqueue('patient y', 1); // highest priority
priorityQueue.enqueue('patient z', 3);
priorityQueue.enqueue('patient w', 4); // lowest priority
priorityQueue.enqueue('patient x', 2);returns the element with highest priority in the queue.
| return | description |
|---|---|
| object | object literal with "priority" and "element" props |
| runtime |
|---|
| O(1) |
console.log(priorityQueue.front()); // { priority: 1, element: 'patient y' }returns an element with lowest priority in the queue. If multiple elements exist at the lowest priority, the one that was inserted first will be returned.
| return | description |
|---|---|
| object | object literal with "priority" and "element" props |
| runtime |
|---|
| O(1) |
priorityQueue.enqueue('patient m', 4); // lowest priority
priorityQueue.enqueue('patient c', 4); // lowest priority
console.log(priorityQueue.back()); // { priority: 4, element: 'patient w' }removes and returns the element with highest priority in the queue.
| return | description |
|---|---|
| object | object literal with "priority" and "element" props |
| runtime |
|---|
| O(log(n)) |
console.log(priorityQueue.dequeue()); // { priority: 1, element: 'patient y' }
console.log(priorityQueue.front()); // { priority: 2, element: 'patient x' }checks if the queue is empty.
| return |
|---|
| boolean |
| runtime |
|---|
| O(1) |
console.log(priorityQueue.isEmpty()); // falsereturns the number of elements in the queue.
| return |
|---|
| number |
| runtime |
|---|
| O(1) |
console.log(priorityQueue.size()); // 5returns a sorted array of elements by their priorities from highest to lowest.
| return | description |
|---|---|
| array | an array of object literals with "priority" & "element" props |
| runtime |
|---|
| O(n*log(n)) |
console.log(priorityQueue.toArray());
/*
[
{ priority: 2, element: 'patient x' },
{ priority: 3, element: 'patient z' },
{ priority: 4, element: 'patient c' },
{ priority: 4, element: 'patient w' },
{ priority: 4, element: 'patient m' }
]
*/clears all elements in the queue.
| runtime |
|---|
| O(1) |
priorityQueue.clear();
console.log(priorityQueue.size()); // 0
console.log(priorityQueue.front()); // null
console.log(priorityQueue.dequeue()); // nullgrunt build
The MIT License. Full License is here