forked from AdaGold/stacks-queues-js
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathqueue.js
More file actions
61 lines (50 loc) · 1.29 KB
/
queue.js
File metadata and controls
61 lines (50 loc) · 1.29 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
const QUEUE_SIZE = 20;
class Queue {
constructor() {
this.store = new Array(QUEUE_SIZE);
this.head = 0;
this.tail = 0;
}
enqueue(element) {
if (this.isFull()) {
throw new Error("your queue is full");
} else {
this.store[this.tail] = element;
this.tail = (this.tail + 1) % QUEUE_SIZE;
}
}
dequeue() {
const element = this.store[this.head];
this.store[this.head] = null;
this.head = (this.head + 1) % QUEUE_SIZE;
return element;
}
front() {
return this.store[this.head];
}
size() {
let count = 0;
let pointer = this.head;
while (this.store[pointer]) {
count++;
pointer = (pointer + 1) % QUEUE_SIZE;
}
return count;
}
isEmpty() {
return this.head === this.tail;
}
isFull() {
return this.head === (this.tail + 1) % QUEUE_SIZE;
}
toString() {
let arr;
if (this.head > this.tail) {
arr = this.store.slice(this.head, this.capacity).concat(this.store.slice(0, this.tail));
} else {
arr = this.store;
}
return JSON.stringify(arr.filter((v) => v !== null));
}
}
module.exports = Queue;