mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2025-12-19 08:59:05 +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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import PriorityQueue from '../PriorityQueue';
|
||||
|
||||
describe('PriorityQueue', () => {
|
||||
it('should create default priority queue', () => {
|
||||
const priorityQueue = new PriorityQueue();
|
||||
|
||||
expect(priorityQueue).toBeDefined();
|
||||
});
|
||||
|
||||
it('should insert items to the queue and respect priorities', () => {
|
||||
const priorityQueue = new PriorityQueue();
|
||||
|
||||
priorityQueue.add(10, 1);
|
||||
expect(priorityQueue.peek()).toBe(10);
|
||||
|
||||
priorityQueue.add(5, 2);
|
||||
expect(priorityQueue.peek()).toBe(10);
|
||||
|
||||
priorityQueue.add(100, 0);
|
||||
expect(priorityQueue.peek()).toBe(100);
|
||||
});
|
||||
|
||||
it('should poll from queue with respect to priorities', () => {
|
||||
const priorityQueue = new PriorityQueue();
|
||||
|
||||
priorityQueue.add(10, 1);
|
||||
priorityQueue.add(5, 2);
|
||||
priorityQueue.add(100, 0);
|
||||
|
||||
expect(priorityQueue.poll()).toBe(100);
|
||||
expect(priorityQueue.poll()).toBe(10);
|
||||
expect(priorityQueue.poll()).toBe(5);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user