Skip to content

Commit ab9c951

Browse files
committed
mvp bfixarrayqueue
1 parent fec1c14 commit ab9c951

File tree

1 file changed

+51
-2
lines changed

1 file changed

+51
-2
lines changed

lib/queues.js

Lines changed: 51 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ class BFltArrayQueue {
9898
}
9999

100100
isFull() {
101-
return this.length === queue.length;
101+
return this.length === this.queue.length;
102102
}
103103

104104
isEmpty() {
@@ -139,7 +139,56 @@ class BFltArrayQueue {
139139
/**
140140
* Implements a bounded queue using an array with the fixed front method.
141141
*/
142-
class BFixArrayQueue {}
142+
class BFixArrayQueue {
143+
constructor(size = (DEFAULT_SIZE = 1000)) {
144+
this.queue = [];
145+
for (let i = 0; i < size; i++) {
146+
this.queue[i] = null;
147+
}
148+
this.rear = -1;
149+
this.length = 0;
150+
}
151+
152+
isFull() {
153+
return this.rear === this.queue.length - 1;
154+
}
155+
156+
isEmpty() {
157+
return this.rear === -1;
158+
}
159+
160+
enqueue(data) {
161+
if (isFull()) {
162+
throw new Error('Enqueue attempted on a full queue.');
163+
} else {
164+
this.rear++;
165+
this.queue[this.rear] = data;
166+
}
167+
}
168+
169+
dequeue() {
170+
if (isEmpty()) {
171+
throw new Error('Dequeue attempted on empty queue.');
172+
} else {
173+
const toReturn = this.queue[0];
174+
175+
// this array shift is why the fixed front method is inefficient.
176+
for (let i = 1; i < this.rear; i++) {
177+
this.queue[i - 1] = this.queue[i];
178+
}
179+
this.rear--;
180+
return toReturn;
181+
}
182+
}
183+
184+
peek() {
185+
return this.queue[this.front];
186+
}
187+
188+
length() {
189+
return this.rear + 1;
190+
}
191+
}
143192

144193
module.exports = {
145194
LinkedQueue,

0 commit comments

Comments
 (0)