881 B
881 B
title, tags, author, cover, firstSeen, lastUpdated
| title | tags | author | cover | firstSeen | lastUpdated |
|---|---|---|---|---|---|
| Cycle generator | function,generator | chalarangelo | secret-tree | 2020-10-11T17:05:38+03:00 | 2020-10-11T17:05:38+03:00 |
Creates a generator, looping over the given array indefinitely.
- Use a non-terminating
whileloop, that willyielda value every timeGenerator.prototype.next()is called. - Use the module operator (
%) withArray.prototype.lengthto get the next value's index and increment the counter after eachyieldstatement.
const cycleGenerator = function* (arr) {
let i = 0;
while (true) {
yield arr[i % arr.length];
i++;
}
};
const binaryCycle = cycleGenerator([0, 1]);
binaryCycle.next(); // { value: 0, done: false }
binaryCycle.next(); // { value: 1, done: false }
binaryCycle.next(); // { value: 0, done: false }
binaryCycle.next(); // { value: 1, done: false }