mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2026-03-13 08:51:02 +08:00
Refactor MinHeap.
This commit is contained in:
23
src/data-structures/priority-queue/PriorityQueue.js
Normal file
23
src/data-structures/priority-queue/PriorityQueue.js
Normal file
@@ -0,0 +1,23 @@
|
||||
import MinHeap from '../heap/MinHeap';
|
||||
|
||||
// It is the same as min heap except that when comparing to elements
|
||||
// we take into account not element's value but rather its priority.
|
||||
export default class PriorityQueue extends MinHeap {
|
||||
constructor() {
|
||||
super();
|
||||
this.priorities = {};
|
||||
}
|
||||
|
||||
add(item, priority = 0) {
|
||||
this.priorities[item] = priority;
|
||||
super.add(item);
|
||||
}
|
||||
|
||||
compare(a, b) {
|
||||
if (this.priorities[a] === this.priorities[b]) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return this.priorities[a] < this.priorities[b] ? -1 : 1;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user