-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathpriority-queue.js
49 lines (40 loc) · 965 Bytes
/
priority-queue.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
class PriorityQueue {
#list = [];
#capacity;
constructor(capacity) {
this.#capacity = Math.max(Number(capacity), 0) || null;
}
get size() {
return this.#list.length;
}
get isFull() {
return this.#capacity !== null && this.size === this.#capacity;
}
get isEmpty() {
return this.size === 0;
}
enqueue(item, priority = 0) {
priority = Math.max(Number(priority), 0);
const element = { item, priority };
if (
this.isEmpty ||
element.priority <= this.#list[this.size - 1].priority
) {
this.#list.push(element);
} else {
for (let index in this.#list) {
if (element.priority > this.#list[index].priority) {
this.#list.splice(index, 0, element);
break;
}
}
}
return this.size;
}
dequeue() {
return this.isEmpty ? null : this.#list.shift().item;
}
toString() {
return this.#list.map((el) => el.item).toString();
}
}