-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathround-linked-queue.js
94 lines (72 loc) · 1.6 KB
/
round-linked-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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
"use strict";
class RoundLinkedQueue {
static fromArray(inputArray) {
const instance = new RoundLinkedQueue(inputArray.length);
inputArray.forEach(el => instance.add(el));
return instance;
}
constructor(maxLength) {
this._maxLength = maxLength;
this._length = 0;
this._first = null;
this._last = null;
}
get maxLength() {
return this._maxLength;
}
get length() {
return this._length;
}
get first() {
if (!this._first) {
throw new Error("Cannot access the first element of an empty queue");
}
return this._first.data;
}
get last() {
if (!this._last) {
throw new Error("Cannot access the last element of an empty queue");
}
return this._last.data;
}
add(element) {
const node = {
data: element,
next: null,
};
let removedNode = {};
if (this.length < this.maxLength) {
if (!this._first) {
this._first = node;
this._last = node;
}
this._length += 1;
} else {
removedNode = this._first;
this._first = this._first.next;
}
this._last.next = node;
this._last = node;
return removedNode.data;
}
remove() {
const removedNode = this._first;
if (!removedNode) {
throw new Error("Cannot remove element from an empty queue");
}
this._first = this._first.next;
this._length -= 1;
return removedNode.data;
}
toArray() {
return [...this]
}
*[Symbol.iterator]() {
let el = this._first;
while (el) {
yield el.data;
el = el.next;
}
}
}
module.exports = RoundLinkedQueue;