-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcircular-queue.js
62 lines (56 loc) · 1.33 KB
/
circular-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
// circular queue
class CircularQueue {
constructor(size) {
this.size = size;
this.rear = -1;
this.front = -1;
this.queue = [];
}
enqueue(item) {// add item ==> return added item
if (this.isFull()) {
return;
}
if (this.front === -1) {
this.front = 0;
}
if (this.rear === this.size - 1) {
this.rear = -1;
}
this.rear++
this.queue[this.rear] = item;
return item
}
dequeue() { // delete item ==> return removed item
if (this.isEmpty()) {
return;
}
const removedItem = this.queue[this.front];
this.queue[this.front] = null;
if (this.front === this.rear) {
this.front = -1;
this.rear = -1;
} else {
if (this.front === this.size - 1) {
this.front = -1
}
this.front++;
}
return removedItem;
}
isFull() { // check queue is full
if (this.front === 0 && this.rear === this.size - 1 || this.front === this.rear + 1) {
console.log('queue is full');
return true;
}
return false;
}
isEmpty() { // check queue is empty
if (this.front === -1) {
console.log('queue is empty');
return true;
}
}
}
const newCircularQueue = new CircularQueue(5);
newCircularQueue.enqueue('ITEM'); // add item
newCircularQueue.dequeue() // return deleted item => pramater => void;