UNPKG

1.34 kBJavaScriptView Raw
1import { Collection } from "../Collection";
2import { MaxHeap } from "../heap/MaxHeap";
3export class PriorityQueueNode {
4 constructor(value, priority) {
5 this.value = value;
6 this.priority = priority;
7 }
8 get Value() {
9 return this.value;
10 }
11 get Priority() {
12 return this.priority;
13 }
14 toString() {
15 return `{"priority":${this.priority},"value":${this.value}}`;
16 }
17}
18export class PriorityQueue extends Collection {
19 constructor() {
20 super();
21 this.heap = new MaxHeap("Priority");
22 }
23 peek() {
24 return this.heap.peek();
25 }
26 enqueue(value, priority) {
27 this.heap.add(new PriorityQueueNode(value, priority));
28 return this;
29 }
30 dequeue() {
31 return this.heap.poll();
32 }
33 changePriority(value, priority) {
34 this.heap.remove(item => item.Value === value);
35 this.heap.add(new PriorityQueueNode(value, priority));
36 }
37 has(value) {
38 return !!this.heap.find(item => item.Value === value);
39 }
40 clear() {
41 this.heap.clear();
42 }
43 isEmpty() {
44 return this.heap.isEmpty();
45 }
46 toString() {
47 return this.heap.toString();
48 }
49 __iterate(fn) {
50 this.heap.entries().forEach((item, index) => fn(item.Value, index));
51 }
52}
53export default PriorityQueue;