lgrthms
Version:
Algorithms and data structures for your JavaScript and TypeScript projects 🧑💻
38 lines (37 loc) • 1.07 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PriorityQueue = void 0;
const MaxHeap_1 = require("./MaxHeap");
class PriorityQueue {
constructor() {
this.MIN_PRIORITY = 0;
const compareFn = (a, b) => a.priority - b.priority;
this.heap = new MaxHeap_1.MaxHeap(compareFn);
}
get size() {
return this.heap.size;
}
// O(log(n)) time | O(1) space
enqueue(value, priority = this.MIN_PRIORITY) {
if (priority < this.MIN_PRIORITY) {
throw new Error('Cannot enqueue value, priority must be greater than or equal to 0');
}
this.heap.insert({ data: value, priority });
return this.heap.size;
}
// O(log(n)) time | O(1) space
dequeue() {
const item = this.heap.extract();
if (item) {
return item.data;
}
}
// O(1) time | O(1) space
peek() {
const item = this.heap.peek();
if (item) {
return item.data;
}
}
}
exports.PriorityQueue = PriorityQueue;