Some minor changes to improve use and protect misuse.
The take
function only takes from the start. It would be more flexible if you pass the generator, not the generator function. That way you can take from a generator where you left off.
function *take(n, values) {
while (n-- > 0) { yield values.next().value }
}
and then used as
take(10, progression()); //to take the first 10
Or
const values = progression();
take(10, values); // take ten
take(10, values); // take ten more
There is a danger someone might use the infinite generator to fill an array
const array = [...progression()]; // uncatchable page crash
Which is an uncatchable error that will crash the page.
You could create an interface that protects the infinity by hiding the progression
in closure. You can also then add some extras if need be.
const progression = (()=>{
function *progression() {
var n = 0;
while (true) { yield n++ }
}
var current = progression();
return {
restart() { current = progression() },
*take(count) {
current = progression();
while (count-- > 0) { yield current.next().value }
},
*more(count) {
while (count-- > 0) { yield current.next().value }
},
get next() { return current.next().value }
};
})();
And used as
progression.take(10); /// get first ten
progression.take(10); /// get first ten again
progression.more(10); /// get ten more
const v = progression.next; // get next value (21st)
progression.restart();
const first = progression.next; // get next value (1st)