Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

timers: fix priority queue removeAt fn #23870

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 6 additions & 1 deletion lib/internal/priority_queue.js
Expand Up @@ -83,8 +83,13 @@ module.exports = class PriorityQueue {
heap[pos] = heap[size + 1];
heap[size + 1] = undefined;

if (size > 0)
if (size > 0) {
// If not removing the last item, update the shifted item's position.
if (pos <= size && this[kSetPosition] !== undefined)
this[kSetPosition](heap[pos], pos);

this.percolateDown(1);
}
}

remove(value) {
Expand Down
36 changes: 36 additions & 0 deletions test/parallel/test-priority-queue.js
Expand Up @@ -95,3 +95,39 @@ const PriorityQueue = require('internal/priority_queue');

assert.strictEqual(queue.peek(), undefined);
}

{
const queue = new PriorityQueue((a, b) => {
return a.value - b.value;
}, (node, pos) => (node.position = pos));

queue.insert({ value: 1, position: null });
queue.insert({ value: 2, position: null });
queue.insert({ value: 3, position: null });
queue.insert({ value: 4, position: null });
queue.insert({ value: 5, position: null });

queue.insert({ value: 2, position: null });
const secondLargest = { value: 10, position: null };
queue.insert(secondLargest);
const largest = { value: 15, position: null };
queue.insert(largest);

queue.removeAt(5);
assert.strictEqual(largest.position, 5);

// check that removing 2nd to last item works fine
queue.removeAt(6);
assert.strictEqual(secondLargest.position, 6);

// check that removing the last item doesn't throw
queue.removeAt(6);

assert.strictEqual(queue.shift().value, 1);
assert.strictEqual(queue.shift().value, 2);
assert.strictEqual(queue.shift().value, 2);
assert.strictEqual(queue.shift().value, 4);
assert.strictEqual(queue.shift().value, 15);

assert.strictEqual(queue.shift(), undefined);
}