-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayBasedImplementation.js
More file actions
62 lines (55 loc) · 1.52 KB
/
ArrayBasedImplementation.js
File metadata and controls
62 lines (55 loc) · 1.52 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
class ArrayBasedImplementation {
constructor() {
this.internalQueue = [];
}
queue(element, priority = 5) {
this.internalQueue.push({
element,
priority
});
}
getHighestPriority() {
if (this.internalQueue.length === 0) return null;
let maxPriority = 10;
for (let i = 0; i < this.internalQueue.length; i++) {
const { priority } = this.internalQueue[i];
if (priority <= maxPriority) maxPriority = priority;
}
return maxPriority;
}
findIndexByPriority(priority) {
const highestPriorityIndex = this.internalQueue.findIndex(
i => i.priority === priority
);
return highestPriorityIndex;
}
peek() {
const highestPriority = this.getHighestPriority();
if (highestPriority) {
const index = this.findIndexByPriority(highestPriority);
const { element } = this.internalQueue[index];
return element;
}
return null;
}
dequeue() {
const highestPriority = this.getHighestPriority();
if (highestPriority) {
const highestPriorityIndex = this.findIndexByPriority(highestPriority);
const { element: dequeuedElement } = this.internalQueue[
highestPriorityIndex
];
const newQueue = [
...this.internalQueue.slice(0, highestPriorityIndex),
...this.internalQueue.slice(highestPriorityIndex + 1)
];
this.internalQueue = newQueue;
return dequeuedElement;
}
return null;
}
clear() {
this.internalQueue = [];
}
}
module.exports = ArrayBasedImplementation;