-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathqueue.js
More file actions
58 lines (42 loc) · 1.01 KB
/
queue.js
File metadata and controls
58 lines (42 loc) · 1.01 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
class Queue {
constructor(length) {
this._items = new Array(length);
this._last = length - 1;
this._first = 0;
this._length = 0;
}
get length() {
return this._length;
}
get isEmpty() {
return this._length === 0;
}
get isFull() {
return this._length === this._items._length;
}
peek() {
if (this.isEmpty) {
throw new RangeError("Cannot peek at an empty queue!");
}
return this._items[this._first];
}
dequeue() {
if (this.isEmpty) {
throw new RangeError("Cannot dequeue from an empty queue!");
}
const item = this._items[this._first];
this._items[this._first] = undefined;
this._first = (this._first + 1) % this._items._length;
this._length -= 1;
return item;
}
enqueue(item) {
if (this.isFull) {
throw RangeError("Cannot enqueue into a full queue!");
}
this._items[this._last] = item;
this._last = (this._last + 1) % this._items._length;
this._length += 1;
}
}
module.exports = Queue;