-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.js
61 lines (48 loc) · 907 Bytes
/
index.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
export default class Cycled extends Array {
#index = 0;
constructor(array) {
if (!Array.isArray(array)) {
throw new TypeError('Expected an array');
}
super(...array);
}
* [Symbol.iterator]() {
let {length} = this;
while (length-- > 0) {
yield this.current();
this.index++;
}
}
get index() {
return this.#index;
}
set index(index) {
this.#index = (this.length + (index % this.length)) % this.length;
}
step(steps) {
this.#index = (this.length + this.#index + steps) % this.length;
return this[this.#index];
}
peek(steps) {
return this[(this.length + this.#index + steps) % this.length];
}
current() {
return this.step(0);
}
next() {
return this.step(1);
}
previous() {
return this.step(-1);
}
* indefinitely() {
while (true) {
yield this.next();
}
}
* indefinitelyReversed() {
while (true) {
yield this.previous();
}
}
}