Refactor MinHeap.

This commit is contained in:
Oleksii Trekhleb
2018-04-03 18:17:14 +03:00
parent 062f5a4929
commit 138c3d9905
5 changed files with 68 additions and 9 deletions

View 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;
}
}