@crstrskp/graph
Version:
High-performance TypeScript graph algorithms library optimized for trading bots and arbitrage detection
79 lines • 2.48 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PriorityQueue = void 0;
class PriorityQueue {
constructor() {
this.heap = [];
}
enqueue(item, priority) {
const newItem = { item, priority };
this.heap.push(newItem);
this.heapifyUp(this.heap.length - 1);
}
dequeue() {
if (this.heap.length === 0)
return undefined;
if (this.heap.length === 1)
return this.heap.pop().item;
const root = this.heap[0];
this.heap[0] = this.heap.pop();
this.heapifyDown(0);
return root.item;
}
peek() {
return this.heap.length > 0 ? this.heap[0].item : undefined;
}
isEmpty() {
return this.heap.length === 0;
}
size() {
return this.heap.length;
}
updatePriority(item, newPriority) {
const index = this.heap.findIndex(queueItem => queueItem.item === item);
if (index === -1)
return false;
const oldPriority = this.heap[index].priority;
this.heap[index].priority = newPriority;
if (newPriority < oldPriority) {
this.heapifyUp(index);
}
else if (newPriority > oldPriority) {
this.heapifyDown(index);
}
return true;
}
heapifyUp(index) {
while (index > 0) {
const parentIndex = Math.floor((index - 1) / 2);
if (this.heap[index].priority >= this.heap[parentIndex].priority)
break;
this.swap(index, parentIndex);
index = parentIndex;
}
}
heapifyDown(index) {
while (true) {
let minIndex = index;
const leftChild = 2 * index + 1;
const rightChild = 2 * index + 2;
if (leftChild < this.heap.length &&
this.heap[leftChild].priority < this.heap[minIndex].priority) {
minIndex = leftChild;
}
if (rightChild < this.heap.length &&
this.heap[rightChild].priority < this.heap[minIndex].priority) {
minIndex = rightChild;
}
if (minIndex === index)
break;
this.swap(index, minIndex);
index = minIndex;
}
}
swap(i, j) {
[this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];
}
}
exports.PriorityQueue = PriorityQueue;
//# sourceMappingURL=PriorityQueue.js.map