-
Notifications
You must be signed in to change notification settings - Fork 0
/
pq.js
82 lines (65 loc) · 1.5 KB
/
pq.js
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
import Heap from './heap.js';
import {Empty} from './lib/tree.js';
const DEFAULT_OPTS = {
invert: false,
compare: function (A, B) {
const {priority:pA = Empty} = A;
const {priority:pB = Empty} = B;
if ( pB == Empty ) {
return 1;
} else if ( pA == Empty ) {
return -1;
}
if ( pA > pB ) {
return -1;
} else if ( pA === pB ) {
return 0;
} else {
return 1;
}
}
};
export default class PQ {
// private fields
// store
#store
// API
// public instance methods
constructor(opts = DEFAULT_OPTS, data) {
opts = Object.assign({}, DEFAULT_OPTS, opts);
const heapOpts = {
invert: opts.invert,
max: true,
compare: opts.compare,
asTree: false,
arity: 4
};
this.#store = new Heap(heapOpts, data);
opts.sign = this.#store.config.sign;
this.config = Object.freeze(opts);
}
isEmpty() {
return this.#store.size === 0;
}
insert(thing, priority) {
const blob = {thing, priority};
this.#store.push(blob);
}
pull() {
return this.#store.pop();
}
top() {
return this.#store.peek();
}
get size() {
return this.#store.size;
}
// static class methods
static print(pq) {
Heap.print(pq.#store, thing => thing.priority);
}
}
export const Class = PQ;
export function create(...args) {
return new PQ(...args);
}