with comparator and delete element functionality
npm install priority-queue-v2Published at - https://www.npmjs.com/package/priority-queue-v2
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)
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'
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))