UNPKG

@thi.ng/heaps

Version:

Various heap implementations for arbitrary values and with customizable ordering

83 lines (82 loc) 1.84 kB
import { compareNumDesc } from "@thi.ng/compare/numeric"; import { equiv } from "@thi.ng/equiv"; import { Heap } from "./heap.js"; const defPriorityQueue = (values, opts) => new PriorityQueue(values, opts); class PriorityQueue { constructor(values, opts = {}) { this.opts = opts; const compare = opts.compare || compareNumDesc; this.heap = new Heap(null, { compare: (a, b) => compare(a[0], b[0]) }); this.equiv = opts.equiv || equiv; values && this.into(values); } heap; equiv; get length() { return this.heap.length; } *[Symbol.iterator]() { yield* this.heap; } clear() { this.heap.clear(); } copy() { return new PriorityQueue(this.heap, this.opts); } empty() { return new PriorityQueue(null, this.opts); } push(val, priority) { this.heap.push([priority, val]); return this; } pushPop(val, priority) { return this.heap.pushPop([priority, val]); } pop() { const res = this.heap.pop(); return res ? res[1] : void 0; } peek() { const res = this.heap.peek(); return res ? res[1] : void 0; } peekPriority() { const res = this.heap.peek(); return res ? res[0] : void 0; } remove(val) { const item = this.find(val); return item ? this.heap.remove(item) : false; } find(val) { return this.heap.findWith((x) => this.equiv(x[1], val)); } findWith(fn) { return this.heap.findWith(fn); } has(val) { return !!this.find(val); } into(values) { this.heap.into(values); return this; } reprioritize(val, priority) { const { heap, equiv: equiv2 } = this; const item = heap.findWith((x) => equiv2(x[1], val)); if (item) { item[0] = priority; heap.heapify(); return true; } return false; } } export { PriorityQueue, defPriorityQueue };