-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueues.js
118 lines (98 loc) · 2.1 KB
/
Queues.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/* Queues */
class Queue {
constructor() {
this.collection = [];
}
print() {
console.log(this.collection);
}
enqueue(...ele) {
this.collection.push(...ele);
}
dequeue() {
return this.collection.shift();
}
front() {
return this.collection[0];
}
size() {
return this.collection.length;
}
isEmpty() {
return (this.collection.length === 0);
}
}
let q = new Queue();
q.enqueue('a', 'b', 'c');
q.print(); //[ 'a', 'b', 'c' ]
q.dequeue();
q.print(); //[ 'b', 'c' ]
console.log(q.front()); //b
class PriorityQueue {
constructor() {
this.collection = [];
}
print() {
console.log(this.collection);
}
enqueue(...ele) {
let sort = ele=> {
if (this.isEmpty()) {
this.collection.push(ele);
} else {
let added = false;
for (let i=0; i<this.collection.length; i++) {
if (ele[1] < this.collection[i][1]) {
this.collection.splice(i,0,ele);
added = true;
break;
}
}
if (!added) {
this.collection.push(ele);
}
}
}
for (let item of ele) {
sort(item);
}
}
dequeue() {
let value = this.collection.shift();
return value[0];
}
front() {
return this.collection[0];
}
size() {
return this.collection.length;
}
isEmpty() {
return (this.collection.length === 0);
}
}
let pq = new PriorityQueue();
pq.enqueue(
['Briana Swift', 2],
['Ewa Mitulska-Wójcik', 1],
['Quincy Larson', 3],
['Beau Carnes', 2]
);
pq.print();
/*
[ [ 'Ewa Mitulska-Wójcik', 1 ],
[ 'Briana Swift', 2 ],
[ 'Beau Carnes', 2 ],
[ 'Quincy Larson', 3 ] ]
*/
pq.dequeue();
console.log(pq.front());
/*
[ 'Briana Swift', 2 ]
*/
pq.print();
/*
[ [ 'Briana Swift', 2 ],
[ 'Beau Carnes', 2 ],
[ 'Quincy Larson', 3 ] ]
; */