forked from loiane/javascript-datastructures-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpriority-queue-array.ts
58 lines (47 loc) · 992 Bytes
/
priority-queue-array.ts
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
import { Compare, defaultCompare, ICompareFunction } from '../util';
export default class PriorityQueue<T> {
private items: T[];
constructor(
private compareFn: ICompareFunction<T> = defaultCompare,
private compare: Compare = Compare.LESS_THAN
) {
this.items = [];
}
enqueue(element: T) {
let added = false;
for (let i = 0; i < this.items.length; i++) {
if (this.compareFn(element, this.items[i]) === this.compare) {
this.items.splice(i, 0, element);
added = true;
break;
}
}
if (!added) {
this.items.push(element);
}
}
dequeue() {
return this.items.shift();
}
peek() {
if (this.isEmpty()) {
return undefined;
}
return this.items[0];
}
isEmpty() {
return this.items.length === 0;
}
clear() {
this.items = [];
}
size() {
return this.items.length;
}
toString() {
if (this.isEmpty()) {
return '';
}
return this.items;
}
}