-
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathcircular-queue.js
More file actions
62 lines (51 loc) · 1.09 KB
/
circular-queue.js
File metadata and controls
62 lines (51 loc) · 1.09 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
class CircularQueue {
#list;
#capacity;
#tail = -1;
#head = -1;
#size = 0;
constructor(capacity = 10) {
this.#capacity = Math.max(Number(capacity), 0) || 10;
this.#list = Array.from({length: this.#capacity});
}
get size() {
return this.#size;
}
get isFull() {
return this.size === this.#capacity;
}
get isEmpty() {
return this.size === 0;
}
enqueue(item) {
if (!this.isFull) {
this.#tail = (this.#tail + 1) % this.#capacity;
this.#list[this.#tail] = item;
this.#size += 1;
if (this.#head === -1) {
this.#head = this.#tail;
}
}
return this.size;
}
dequeue() {
let item = null;
if (!this.isEmpty) {
item = this.#list[this.#head];
delete this.#list[this.#head];
this.#head = (this.#head + 1) % this.#capacity;
this.#size -= 1;
if (!this.size) {
this.#head = -1;
this.#tail = -1;
}
}
return item;
}
peek() {
return this.#list[this.#head];
}
toString() {
return this.#list.filter((el) => el !== undefined).toString();
}
}