1 | import { Collection } from "../Collection";
|
2 | import { Heap } from "../heap/Heap";
|
3 | import { MaxHeap } from "../heap/MaxHeap";
|
4 |
|
5 | export class PriorityQueueNode<T>{
|
6 | constructor(private value: T, private priority: number){
|
7 |
|
8 | }
|
9 |
|
10 | public get Value(){
|
11 | return this.value;
|
12 | }
|
13 |
|
14 | public get Priority(){
|
15 | return this.priority;
|
16 | }
|
17 |
|
18 | public toString(){
|
19 | return `{"priority":${this.priority},"value":${this.value}}`;
|
20 | }
|
21 | }
|
22 |
|
23 | export class PriorityQueue<T> extends Collection<T>{
|
24 | private heap: Heap<PriorityQueueNode<T>>;
|
25 | constructor(){
|
26 | super();
|
27 | this.heap = new MaxHeap<PriorityQueueNode<T>>("Priority");
|
28 | }
|
29 |
|
30 | |
31 |
|
32 |
|
33 | public peek(){
|
34 | return this.heap.peek();
|
35 | }
|
36 |
|
37 | |
38 |
|
39 |
|
40 |
|
41 |
|
42 | public enqueue(value: T, priority: number){
|
43 | this.heap.add(new PriorityQueueNode(value, priority));
|
44 | return this;
|
45 | }
|
46 |
|
47 | |
48 |
|
49 |
|
50 | public dequeue(){
|
51 | return this.heap.poll();
|
52 | }
|
53 |
|
54 | |
55 |
|
56 |
|
57 |
|
58 |
|
59 | public changePriority(value: T, priority: number){
|
60 | this.heap.remove(item => item.Value === value);
|
61 | this.heap.add(new PriorityQueueNode(value, priority));
|
62 | }
|
63 |
|
64 | |
65 |
|
66 |
|
67 |
|
68 |
|
69 | public has(value: T){
|
70 | return !!this.heap.find(item => item.Value === value);
|
71 | }
|
72 |
|
73 | |
74 |
|
75 |
|
76 | public clear(){
|
77 | this.heap.clear();
|
78 | }
|
79 |
|
80 | |
81 |
|
82 |
|
83 | public isEmpty(){
|
84 | return this.heap.isEmpty();
|
85 | }
|
86 |
|
87 | |
88 |
|
89 |
|
90 | public toString() {
|
91 | return this.heap.toString();
|
92 | }
|
93 |
|
94 | protected __iterate(fn: (item: T, index: number) => void): void {
|
95 | this.heap.entries().forEach((item, index) => fn(item.Value, index));
|
96 | }
|
97 | }
|
98 |
|
99 | export default PriorityQueue;
|