Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 7 additions & 12 deletions lib/internal/priority_queue.js
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -12,7 +8,7 @@ const {

module.exports = class PriorityQueue {
#compare = (a, b) => a - b;
#heap = new Array(64);
#heap = [undefined, undefined];
#setPosition;
#size = 0;

Expand All @@ -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);
}

Expand All @@ -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;
Expand All @@ -62,22 +56,23 @@ module.exports = class PriorityQueue {

if (compare(item, childItem) <= 0) break;

if (setPosition !== undefined)
if (hasSetPosition)
setPosition(childItem, pos);

heap[pos] = childItem;
pos = child;
}

heap[pos] = item;
if (setPosition !== undefined)
if (hasSetPosition)
setPosition(item, pos);
}

percolateUp(pos) {
const heap = this.#heap;
const compare = this.#compare;
const setPosition = this.#setPosition;
const hasSetPosition = setPosition !== undefined;
const item = heap[pos];

while (pos > 1) {
Expand All @@ -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);
}

Expand Down
Loading