From c6ed8a48db46db8864265c8dd91804d048639d9d Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 11 Oct 2020 17:05:48 +0300 Subject: [PATCH] Add repeatGenerator --- snippets/repeatGenerator.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 snippets/repeatGenerator.md diff --git a/snippets/repeatGenerator.md b/snippets/repeatGenerator.md new file mode 100644 index 000000000..45b93a295 --- /dev/null +++ b/snippets/repeatGenerator.md @@ -0,0 +1,27 @@ +--- +title: repeatGenerator +tags: function,generator,advanced +--- + +Creates a generator, repeating the given value indefinitely. + +- Use a non-terminating `while` loop, that will `yield` a value every time `Generator.prototype.next()` is called. +- Use the return value of the `yield` statement to update the returned value if the passed value is not `undefined`. + +```js +const repeatGenerator = function* (val) { + let v = val; + while (true) { + let newV = yield v; + if (newV !== undefined) v = newV; + } +}; +``` + +```js +const repeater = repeatGenerator(5); +repeater.next(); // { value: 5, done: false } +repeater.next(); // { value: 5, done: false } +repeater.next(4); // { value: 4, done: false } +repeater.next(); // { value: 4, done: false } +```