-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.js
82 lines (75 loc) · 1.97 KB
/
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
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
function Queue(){
// this will be our collection.
let collection = [];
// this prints the entire queue.
this.print = function(){
console.log(collection);
}
// this method pushes an element into the queue.
this.enqueue = function(element){
collection.push(element);
}
// this will delete an element from queue
this.dequeue = function(){
return collection.shift();
}
// this will return the element at the front
this.front = function(element){
return collection[0];
};
// returns the size of queue
this.size = function(){
return collection.length;
}
}
let queueOne = new Queue();
queueOne.enqueue('hello');
queueOne.enqueue('world');
queueOne.dequeue();
queueOne.print()
// priority queue.
function PriorityQueue () {
var collection = [];
this.printCollection = function() {
(console.log(collection));
};
this.enqueue = function(element){
if (this.isEmpty()){
collection.push(element);
} else {
var added = false;
for (var i=0; i<collection.length; i++){
if (element[1] < collection[i][1]){ //checking priorities
collection.splice(i,0,element);
added = true;
break;
}
}
if (!added){
collection.push(element);
}
}
};
this.dequeue = function() {
var value = collection.shift();
return value[0];
};
this.front = function() {
return collection[0];
};
this.size = function() {
return collection.length;
};
this.isEmpty = function() {
return (collection.length === 0);
};
}
var pq = new PriorityQueue();
pq.enqueue(['prashant', 2]);
pq.enqueue(['Raj', 3]);
pq.enqueue(['Ram', 1])
pq.enqueue(['jhon', 2])
pq.printCollection();
pq.dequeue();
console.log(pq.front());
pq.printCollection();