UNPKG

@panyam/priorityq

Version:

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

67 lines 1.72 kB
import { Storage } from "./storage"; class ListPQHandle { constructor(value, index) { this.value = value; this.index = index; } } export class ListStorage extends Storage { constructor() { super(...arguments); this.handles = []; } get size() { return this.handles.length; } clear() { this.handles = []; } adjust(_handle) { } get isEmpty() { return this.handles.length == 0; } get top() { const [_, handle] = this.minIndex; return handle; } push(value) { const handle = new ListPQHandle(value, this.handles.length); this.handles.push(handle); return handle; } pop() { const [_, handle] = this.minIndex; return this.remove(handle); } remove(handle) { const index = handle.index; this.handles.splice(index, 1); for (let i = index; i < this.handles.length; i++) { this.handles[i].index = i; } return handle; } get sortedHandles() { const out = [...this.handles]; const cmpFunc = this.comparator; out.sort((x, y) => cmpFunc(x.value, y.value)); return out.values(); } get minIndex() { if (this.isEmpty) { throw new Error("Storage is empty."); } let index = -1; let handle; for (let i = 0; i < this.handles.length; i++) { const h = this.handles[i]; if (index < 0 || this.comparator(h.value, handle.value) < 0) { index = i; handle = h; } } return [index, handle]; } } //# sourceMappingURL=list.js.map