Repeat generator
JavaScript, Function, Generator · Oct 11, 2020

Creates a generator, repeating the given value indefinitely.
- Use a non-terminating
while
loop, that willyield
a value every timeGenerator.prototype.next()
is called. - Use the return value of the
yield
statement to update the returned value if the passed value is notundefined
.
const repeatGenerator = function* (val) {
let v = val;
while (true) {
let newV = yield v;
if (newV !== undefined) v = newV;
}
};
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 }
Written by Angelos Chalaris
I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.
If you want to keep in touch, follow me on GitHub.