priority-queue-v2
Published at - https://www.npmjs.com/package/priority-queue-v2
Operations supported -
queue - add an element to the queue
dequeue - delete the max priority element from the queue
isEmpty - returns true/false
clear - clear the queue
delete - If we need to update the priority, delete that item and insert it in again
list - contents of heap
The Item stored in the queue should be class and a comparator should be provided.
By default, duplicate elements are not allowed.
To allow duplicates in the queue add the allowDuplicates argument to true.
let obj = new PriorityQueue(comparator, true)
Examples -
We need max priority element to be removed first. 1. If values in a queue are strings, comparator will receive priorities as a and b in the example below
let comparator = function (a, b) {
return a >= b ? false : true
}
An example would be -
const PriorityQueue = require('../index.js').priorityQueue let obj = new PriorityQueue(comparator) obj.queue('c', 1) obj.queue('b', 3) obj.queue('a', 5) console.log(obj.dequeue()) //'a'
2. If values in the queue is an object, comparator will receive the object and you need to compare priorities as seen below -
class Box { constructor(w, l) { this.w = w this.l = l this.area = w * l //this is priority } comparator(a, b) { return a.area >= b.area ? false : true } } let obj = new PriorityQueue(Box.prototype.comparator) obj.queue(new Box(5, 5)) obj.queue(new Box(2, 3)) obj.queue(new Box(3, 3)) obj.queue(new Box(9, 9)) assert.deepEqual(obj.dequeue(), new Box(9, 9)) assert.deepEqual(obj.dequeue(), new Box(5, 5))