UNPKG

2.13 kBPlain TextView Raw
1import { Collection } from "../Collection";
2import { Heap } from "../heap/Heap";
3import { MaxHeap } from "../heap/MaxHeap";
4
5export 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
23export 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 * @param value 节点的值
40 * @param priority 节点的优先级
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 * @param value
57 * @param priority
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 * @param value
67 * @returns boolean
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 * @returns string
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
99export default PriorityQueue;