-
Notifications
You must be signed in to change notification settings - Fork 154
/
implement-queue-using-fixed-size-array.js
67 lines (54 loc) · 1.21 KB
/
implement-queue-using-fixed-size-array.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
/**
* Implement a Queue with Fixed-Size Array
*/
class Queue {
constructor(capacity) {
this.capacity = capacity;
this.size = 0;
this.front = 0;
this.rear = capacity - 1;
this.array = Array(capacity);
}
// Queue is full when size becomes equal to the capacity
isFull() {
return this.size === this.capacity;
}
// Queue is empty when size is 0
isEmpty() {
return this.size === 0;
}
// Method to add an item to the queue.
// It changes rear and size
enqueue(item) {
if (this.isFull()) {
return;
}
this.rear = (this.rear + 1) % this.capacity;
this.array[this.rear] = item;
this.size += 1;
}
// Method to remove an item from queue.
// It changes front and size
dequeue() {
if (this.isEmpty()) {
throw new Error('Queue is Empty');
}
const item = this.array[this.front];
this.front = (this.front + 1) % this.capacity;
this.size -= 1;
return item;
}
front() {
if (this.isEmpty()) {
throw new Error('Queue is Empty');
}
return this.array[this.front];
}
rear() {
if (this.isEmpty()) {
throw new Error('Queue is Empty');
}
return this.array[this.rear];
}
}
export { Queue };