-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.js
64 lines (52 loc) · 1.45 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
class Queue {
constructor() {
this.items = [];
}
enqueue(item) {
// this.items[this.items.length] = item;
this.items.push(item);
}
dequeue() {
if (this.isEmpty()) {
return "Queue is empty"
}
// let item = this.items[0];
// this.items.splice(0, 1);
// return item;
return this.items.shift();
}
isEmpty() {
return this.items.length === 0;
}
peek() {
return this.items[0];
}
search(item) {
// for (let i = 0; i < this.items.length - 1; i++) {
// if (this.items[i] === item) {
// return i;
// }
// }
// return null
let index = this.items.indexOf(item);
return (index !== -1) ? index : null;
}
print() {
return this.items.toString();
}
}
let queue = new Queue();
console.log('Is queue Empty : ', queue.isEmpty());
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
queue.enqueue(4)
queue.enqueue(5)
console.log('Is queue Empty : ', queue.isEmpty());
console.log('Print the queue : ', queue.print())
console.log('Lookup for peek value : ', queue.peek())
console.log('Pop out top value : ', queue.dequeue())
console.log('Lookup for peek value : ', queue.peek())
console.log('Search index for value 3 : ', queue.search(3))
console.log('Search index for value 10 : ', queue.search(10))
console.log('Print the queue : ', queue.print())