UNPKG

@panyam/priorityq

Version:

A Priority Queue implementation with O(1) lookups for lookup by value.

101 lines 2.75 kB
import { BinHeapStorage } from "./binheap"; function idKeyFunc(x) { return x; } export class PQ { constructor(comparatorOrStorage, keyFunc = idKeyFunc) { this.handlesByValue = new Map(); this.keyFunc = keyFunc; if ("heapify" in comparatorOrStorage) { this.storage = comparatorOrStorage; } else { const comparator = comparatorOrStorage; this.storage = new BinHeapStorage(comparator); } } get top() { return this.storage.top; } pop() { const handle = this.storage.pop(); const key = this.keyFunc(handle.value); const handleEntry = this.handlesByValue.get(key) || null; if (handleEntry == null) return null; if (handleEntry[1] == 1) { this.handlesByValue.delete(key); } else { handleEntry[1]--; } return handle.value; } push(value) { const key = this.keyFunc(value); let handleEntry = this.handlesByValue.get(key) || null; if (handleEntry == null) { const handle = this.storage.push(value); handleEntry = [handle, 0]; this.handlesByValue.set(key, handleEntry); } handleEntry[1]++; return handleEntry[0]; } heapify(values) { for (const value of values) { this.push(value); } } adjustValue(value) { const handle = this.find(value); if (handle == null) { this.push(value); } else { this.adjust(handle); } } adjust(handle) { this.storage.adjust(handle); } removeValue(value) { const handle = this.find(value); if (handle != null) { this.remove(handle); } } remove(handle) { const key = this.keyFunc(handle.value); const handleEntry = this.handlesByValue.get(key) || [null, -1]; const [foundHandle, count] = handleEntry; if (foundHandle != null) { if (count > 1) { handleEntry[1]--; } else { this.storage.remove(foundHandle); this.handlesByValue.delete(key); } } } findByKey(key) { const [handle, _] = this.handlesByValue.get(key) || [null, -1]; return handle; } find(value) { const key = this.keyFunc(value); return this.findByKey(key); } get size() { return this.storage.size; } get isEmpty() { return this.storage.isEmpty; } clear() { this.storage.clear(); this.handlesByValue = new Map(); } } //# sourceMappingURL=pq.js.map