-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
51 lines (46 loc) · 1.23 KB
/
Copy pathindex.js
File metadata and controls
51 lines (46 loc) · 1.23 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
class PriorityQueue {
constructor() {
this.queue = [];
}
// Add an element to the queue with a given priority
enqueue(element, priority) {
const item = { element, priority };
if (this.isEmpty()) {
this.queue.push(item);
} else {
let added = false;
for (let i = 0; i < this.queue.length; i++) {
if (item.priority > this.queue[i].priority) {
this.queue.splice(i, 0, item);
added = true;
break;
}
}
if (!added) {
this.queue.push(item);
}
}
}
// Remove and return the element with the highest priority
dequeue() {
if (this.isEmpty()) {
return "Queue is empty!";
}
return this.queue.shift();
}
// View the element with the highest priority without removing it
peek() {
if (this.isEmpty()) {
return "Queue is empty!";
}
return this.queue[0];
}
// Check if the queue is empty
isEmpty() {
return this.queue.length === 0;
}
// Get the size of the queue
size() {
return this.queue.length;
}
}