-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpriority-queue.js
More file actions
87 lines (74 loc) · 2.04 KB
/
priority-queue.js
File metadata and controls
87 lines (74 loc) · 2.04 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
class Node {
constructor(value, priority) {
this.value = value;
this.priority = priority;
}
}
class PriorityQueue {
constructor() {
this.items = [];
}
enqueue(value, priority) {
let node = new Node(value, priority);
for (let i = 0; i < this.items.length; i++) {
if (node.priority > this.items[i].priority) {
this.items.splice(i, 0, node);
return true;
}
}
this.items.push(node);
}
dequeue() {
if (this.isEmpty()) {
return "Queue is empty"
}
return this.items.shift();
}
isEmpty() {
return this.items.length === 0;
}
front() {
if (this.isEmpty()) {
return "Queue is empty"
}
return this.items[0];
}
rear() {
if (this.isEmpty()) {
return "Queue is empty"
}
return this.items[this.items.length - 1];
}
search(item) {
for (let i = 0; i < this.items.length; i++) {
if (this.items[i].value === item) {
return i;
}
}
return null;
}
print() {
var str = "";
for (var i = 0; i < this.items.length; i++) {
str += this.items[i].value + " ";
}
return str;
}
}
let queue = new PriorityQueue();
console.log('Is queue Empty : ', queue.isEmpty());
queue.enqueue(1, 1);
queue.enqueue(2, 2);
queue.enqueue(3, 1);
queue.enqueue(4, 2);
queue.enqueue(5, 1);
console.log('Is queue Empty : ', queue.isEmpty());
console.log('Print the queue : ', queue.print())
console.log('Lookup for front value : ', queue.front());
console.log('Print the queue : ', queue.print())
console.log('Pop out top value : ', queue.dequeue())
console.log('Print the queue : ', queue.print())
console.log('Lookup for front value : ', queue.front());
console.log('Search index for value 4 : ', queue.search(4))
console.log('Search index for value 10 : ', queue.search(10))
console.log('Print the queue : ', queue.print())