UNPKG

yqueue

Version:

Yet another concurrent task queue

78 lines 2.62 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BinaryHeap = void 0; class BinaryHeap { constructor(compare) { this.compare = compare; this.values = []; } get length() { return this.values.length; } add(element) { this.values.push(element); let index = this.values.length - 1; const current = this.values[index]; try { while (index > 0) { const parentIndex = Math.floor((index - 1) / 2); const parent = this.values[parentIndex]; if (this.compare(parent, current) < 0) { this.values[parentIndex] = current; this.values[index] = parent; index = parentIndex; } else break; } } catch (e) { // compare function throws an error. this.values.pop(); throw e; } } peek() { var _a; return (_a = this.values[0]) !== null && _a !== void 0 ? _a : null; } removeMax() { var _a; if (this.values.length <= 1) return (_a = this.values.pop()) !== null && _a !== void 0 ? _a : null; const max = this.values[0]; const end = this.values[this.values.length - 1]; this.values[0] = end; this.values.pop(); let index = 0; const length = this.values.length; const current = this.values[0]; for (;;) { const leftChildIndex = 2 * index + 1; const rightChildIndex = 2 * index + 2; let leftChild = null; let rightChild = null; let swap = null; if (leftChildIndex < length) { leftChild = this.values[leftChildIndex]; if (this.compare(leftChild, current) > 0) swap = leftChildIndex; if (rightChildIndex < length) { rightChild = this.values[rightChildIndex]; if ((swap === null && this.compare(rightChild, current) > 0) || (swap !== null && this.compare(rightChild, leftChild) > 0)) { swap = rightChildIndex; } } } if (swap === null) break; this.values[index] = this.values[swap]; this.values[swap] = current; index = swap; } return max; } } exports.BinaryHeap = BinaryHeap; //# sourceMappingURL=binary-heap.js.map