UNPKG

@js-sdsl/priority-queue

Version:

javascript standard data structure library which benchmark against C++ STL

128 lines (123 loc) 2.76 kB
"use strict"; Object.defineProperty(exports, "t", { value: true }); class Base { constructor() { this.i = 0; } get length() { return this.i; } size() { return this.i; } empty() { return this.i === 0; } } class PriorityQueue extends Base { constructor(t = [], s = function(t, s) { if (t > s) return -1; if (t < s) return 1; return 0; }, i = true) { super(); this.h = s; if (Array.isArray(t)) { this.u = i ? [ ...t ] : t; } else { this.u = []; const s = this; t.forEach((function(t) { s.u.push(t); })); } this.i = this.u.length; const h = this.i >> 1; for (let t = this.i - 1 >> 1; t >= 0; --t) { this.o(t, h); } } l(t) { const s = this.u[t]; while (t > 0) { const i = t - 1 >> 1; const h = this.u[i]; if (this.h(h, s) <= 0) break; this.u[t] = h; t = i; } this.u[t] = s; } o(t, s) { const i = this.u[t]; while (t < s) { let s = t << 1 | 1; const h = s + 1; let e = this.u[s]; if (h < this.i && this.h(e, this.u[h]) > 0) { s = h; e = this.u[h]; } if (this.h(e, i) >= 0) break; this.u[t] = e; t = s; } this.u[t] = i; } clear() { this.i = 0; this.u.length = 0; } push(t) { this.u.push(t); this.l(this.i); this.i += 1; } pop() { if (this.i === 0) return; const t = this.u[0]; const s = this.u.pop(); this.i -= 1; if (this.i) { this.u[0] = s; this.o(0, this.i >> 1); } return t; } top() { return this.u[0]; } find(t) { return this.u.indexOf(t) >= 0; } remove(t) { const s = this.u.indexOf(t); if (s < 0) return false; if (s === 0) { this.pop(); } else if (s === this.i - 1) { this.u.pop(); this.i -= 1; } else { this.u.splice(s, 1, this.u.pop()); this.i -= 1; this.l(s); this.o(s, this.i >> 1); } return true; } updateItem(t) { const s = this.u.indexOf(t); if (s < 0) return false; this.l(s); this.o(s, this.i >> 1); return true; } toArray() { return [ ...this.u ]; } } exports.PriorityQueue = PriorityQueue; //# sourceMappingURL=index.js.map