-
Notifications
You must be signed in to change notification settings - Fork 0
/
PriorityQueue.js
60 lines (56 loc) · 1.48 KB
/
PriorityQueue.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
class PriorityQueue {
// Initialize data and length
constructor() {
this.data = []
this.length = 0;
}
// enqueue according to priority
enqueue(val, priority = 0) {
// Error handeling check
if (val == undefined || val == null) return;
let added = false;
for (let i = 0; i < this.length; i++) {
if (this.data[i].priority > priority) {
// add to this.data
this.data.splice(i, 0, {
val: val,
priority: priority
})
this.length += 1;
added = true;
return;
}
}
// add to data if this.length=0 or priority is greater then all previous priority
if (!added) {
this.data.push({
val: val,
priority: priority
});
this.length += 1;
return;
}
}
// Remove element from queue return lowest priority one
dequeue() {
if (this.length == 0) return;
this.length -= 1;
return this.data.splice(0, 1)
}
size() {
return this.length;
}
peek() {
return this.data[0];
}
getAllVal() {
const val = [];
this.data.forEach(d => val.push(d.val))
return val;
}
getAllPriority() {
const priority = [];
this.data.forEach(d => priority.push(d.priority))
return priority;
}
}