forked from sindresorhus/cycled
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
58 lines (46 loc) · 848 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
'use strict';
module.exports = class Cycled extends Array {
constructor(array) {
if (!Array.isArray(array)) {
throw new TypeError('Expected an array');
}
super(...array);
this._index = 0;
}
* [Symbol.iterator]() {
let {length} = this;
while (length-- > 0) {
yield this.next();
}
}
* indefinitely() {
while (true) {
yield this.next();
}
}
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];
}
current() {
return this.step(0);
}
next() {
return this.step(1);
}
previous() {
return this.step(-1);
}
* indefinitelyReversed() {
const _this = this;
while (true) {
yield _this.previous();
}
}
};