From 3f32b58ef4bbc4cf0c2fc840ff03627d23555abb Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 11 Oct 2020 17:05:38 +0300 Subject: [PATCH] Add cycleGenerator --- snippets/cycleGenerator.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 snippets/cycleGenerator.md diff --git a/snippets/cycleGenerator.md b/snippets/cycleGenerator.md new file mode 100644 index 000000000..586b6fff9 --- /dev/null +++ b/snippets/cycleGenerator.md @@ -0,0 +1,27 @@ +--- +title: cycleGenerator +tags: function,generator,advanced +--- + +Creates a generator, looping over the given array indefinitely. + +- Use a non-terminating `while` loop, that will `yield` a value every time `Generator.prototype.next()` is called. +- Use the module operator (`%`) with `Array.prototype.length` to get the next value's index and increment the counter after each `yield` statement. + +```js +const cycleGenerator = function* (arr) { + let i = 0; + while (true) { + yield arr[i % arr.length]; + i++; + } +}; +``` + +```js +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 } +```