diff --git a/lib/internal/priority_queue.js b/lib/internal/priority_queue.js index 84db200b1cea96..22f89a90ef07f1 100644 --- a/lib/internal/priority_queue.js +++ b/lib/internal/priority_queue.js @@ -2,14 +2,8 @@ const { Array, - Symbol, } = primordials; -const kCompare = Symbol('compare'); -const kHeap = Symbol('heap'); -const kSetPosition = Symbol('setPosition'); -const kSize = Symbol('size'); - // The PriorityQueue is a basic implementation of a binary heap that accepts // a custom sorting function via its constructor. This function is passed // the two nodes to compare, similar to the native Array#sort. Crucially @@ -17,23 +11,21 @@ const kSize = Symbol('size'); // just a single criteria. module.exports = class PriorityQueue { + #compare = (a, b) => a - b; + #heap = new Array(64); + #setPosition; + #size = 0; + constructor(comparator, setPosition) { if (comparator !== undefined) - this[kCompare] = comparator; + this.#compare = comparator; if (setPosition !== undefined) - this[kSetPosition] = setPosition; - - this[kHeap] = new Array(64); - this[kSize] = 0; - } - - [kCompare](a, b) { - return a - b; + this.#setPosition = setPosition; } insert(value) { - const heap = this[kHeap]; - const pos = ++this[kSize]; + const heap = this.#heap; + const pos = ++this.#size; heap[pos] = value; if (heap.length === pos) @@ -43,14 +35,14 @@ module.exports = class PriorityQueue { } peek() { - return this[kHeap][1]; + return this.#heap[1]; } percolateDown(pos) { - const compare = this[kCompare]; - const setPosition = this[kSetPosition]; - const heap = this[kHeap]; - const size = this[kSize]; + const compare = this.#compare; + const setPosition = this.#setPosition; + const heap = this.#heap; + const size = this.#size; const item = heap[pos]; while (pos * 2 <= size) { @@ -71,9 +63,9 @@ module.exports = class PriorityQueue { } percolateUp(pos) { - const heap = this[kHeap]; - const compare = this[kCompare]; - const setPosition = this[kSetPosition]; + const heap = this.#heap; + const compare = this.#compare; + const setPosition = this.#setPosition; const item = heap[pos]; while (pos > 1) { @@ -91,13 +83,13 @@ module.exports = class PriorityQueue { } removeAt(pos) { - const heap = this[kHeap]; - const size = --this[kSize]; + const heap = this.#heap; + const size = --this.#size; heap[pos] = heap[size + 1]; heap[size + 1] = undefined; if (size > 0 && pos <= size) { - if (pos > 1 && this[kCompare](heap[pos / 2 | 0], heap[pos]) > 0) + if (pos > 1 && this.#compare(heap[pos / 2 | 0], heap[pos]) > 0) this.percolateUp(pos); else this.percolateDown(pos); @@ -105,7 +97,7 @@ module.exports = class PriorityQueue { } shift() { - const heap = this[kHeap]; + const heap = this.#heap; const value = heap[1]; if (value === undefined) return;