Repository navigation
Expand file tree
/
Copy pathpriority-queue.ts
More file actions
150 lines (125 loc) · 2.94 KB
/
Copy pathpriority-queue.ts
File metadata and controls
150 lines (125 loc) · 2.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
interface QueueEntry<T> {
value: T;
prev: QueueEntry<T>;
next: QueueEntry<T>;
}
export class PriorityQueue<T extends object> implements Iterable<T> {
private lookup = new WeakMap<T, QueueEntry<T>>();
private begin: QueueEntry<T> = null;
private end: QueueEntry<T> = null;
private _size = 0;
constructor(private readonly predicate: (a: T, b: T) => number) {}
get size(): number {
return this._size;
}
enqueue(value: T): void {
let entry: QueueEntry<T>;
if (this.end === null) {
this.begin =
this.end =
entry =
{
value,
prev: null,
next: null,
};
} else {
let p = this.end;
while (p && this.predicate(p.value, value) > 0) {
p = p.prev;
}
if (!p) {
// beginning
entry = { value, prev: null, next: this.begin };
this.begin.prev = entry;
this.begin = entry;
} else if (!p.next) {
// end
entry = { value, prev: p, next: null };
this.end.next = entry;
this.end = entry;
} else {
// in between
entry = { value, prev: p, next: p.next };
p.next.prev = entry;
p.next = entry;
}
}
this.lookup.set(value, entry);
this._size++;
}
resort(): void {
if (this._size < 2) {
return;
}
let p = this.begin.next;
while (p !== null) {
let q = p.prev;
const n = p.next;
while (q && this.predicate(q.value, p.value) > 0) {
q = q.prev;
}
if (q !== p.prev) {
if (p.prev) {
p.prev.next = p.next;
}
if (p.next) {
p.next.prev = p.prev;
} else {
this.end = p.prev;
this.end.next = null;
}
if (q) {
q.next.prev = p;
p.next = q.next;
q.next = p;
p.prev = q;
} else {
p.next = this.begin;
p.prev = null;
this.begin.prev = p;
this.begin = p;
}
}
p = n;
}
}
dequeue(): T {
if (this._size === 0) {
return null;
}
const value = this.begin.value;
if (this.begin.next) {
this.begin.next.prev = null;
}
this.begin = this.begin.next;
this._size--;
this.lookup.delete(value);
return value;
}
remove(value: T): void {
if (!this.lookup.has(value)) {
return;
}
const entry = this.lookup.get(value);
if (entry.prev && entry.next) {
entry.prev.next = entry.next;
entry.next.prev = entry.prev;
} else if (entry.next) {
entry.next.prev = null;
this.begin = entry.next;
} else if (entry.prev) {
entry.prev.next = null;
this.end = entry.prev;
} else {
this.end = this.begin = null;
}
this.lookup.delete(value);
this._size--;
}
*[Symbol.iterator](): Iterator<T> {
for (let p = this.begin; p != null; p = p.next) {
yield p.value;
}
}
}