-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
queue.js
96 lines (73 loc) · 1.5 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
class Queue {
#list = [];
#capacity = null;
#tail = 0;
#head = 0;
constructor(capacity) {
this.#capacity = Math.max(Number(capacity), 0) || null;
if(this.#capacity) {
this.#list = Array.from({length: this.#capacity});
}
}
get size() {
return this.#tail - this.#head;
}
get isEmpty() {
return this.size === 0;
}
get isFull() {
return this.#capacity && this.#tail === this.#capacity;
}
enqueue(item) {
if(!this.isFull) {
this.#list[this.#tail] = item;
this.#tail += 1;
}
return this.size;
}
dequeue() {
let item = null;
if(!this.isEmpty) {
item = this.#list[this.#head];
delete this.#list[this.#head];
this.#head += 1;
if(this.isEmpty) {
this.#head = 0;
this.#tail = 0;
}
}
return item;
}
peek() {
if(this.isEmpty) {
return null;
}
return this.#list[this.#head];
}
clear() {
if(this.#capacity) {
this.#list = Array.from({length: this.#capacity});
} else {
this.#list = [];
}
this.#head = 0;
this.#tail = 0;
}
print() {
const list = [];
this.#list.forEach(item => {
list.push(item);
})
console.log(list)
}
toString() {
if(this.isEmpty) {
return '';
}
let str = `${this.#list[this.#head]}`;
for(let i = this.#head+1; i < this.#tail; i++) {
str += `, ${this.#list[i]}`;
}
return str;
}
}