diff --git a/lib/internal/priority_queue.js b/lib/internal/priority_queue.js index c172e2351c93ab..e6fdb61e9997c9 100644 --- a/lib/internal/priority_queue.js +++ b/lib/internal/priority_queue.js @@ -1,9 +1,5 @@ 'use strict'; -const { - Array, -} = primordials; - // 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 @@ -12,7 +8,7 @@ const { module.exports = class PriorityQueue { #compare = (a, b) => a - b; - #heap = new Array(64); + #heap = [undefined, undefined]; #setPosition; #size = 0; @@ -28,9 +24,6 @@ module.exports = class PriorityQueue { const pos = ++this.#size; heap[pos] = value; - if (heap.length === pos) - heap.length *= 2; - this.percolateUp(pos); } @@ -45,6 +38,7 @@ module.exports = class PriorityQueue { percolateDown(pos) { const compare = this.#compare; const setPosition = this.#setPosition; + const hasSetPosition = setPosition !== undefined; const heap = this.#heap; const size = this.#size; const hsize = size >> 1; @@ -62,7 +56,7 @@ module.exports = class PriorityQueue { if (compare(item, childItem) <= 0) break; - if (setPosition !== undefined) + if (hasSetPosition) setPosition(childItem, pos); heap[pos] = childItem; @@ -70,7 +64,7 @@ module.exports = class PriorityQueue { } heap[pos] = item; - if (setPosition !== undefined) + if (hasSetPosition) setPosition(item, pos); } @@ -78,6 +72,7 @@ module.exports = class PriorityQueue { const heap = this.#heap; const compare = this.#compare; const setPosition = this.#setPosition; + const hasSetPosition = setPosition !== undefined; const item = heap[pos]; while (pos > 1) { @@ -86,13 +81,13 @@ module.exports = class PriorityQueue { if (compare(parentItem, item) <= 0) break; heap[pos] = parentItem; - if (setPosition !== undefined) + if (hasSetPosition) setPosition(parentItem, pos); pos = parent; } heap[pos] = item; - if (setPosition !== undefined) + if (hasSetPosition) setPosition(item, pos); }