Thursday, September 28, 2017

Javascript Puzzle No.1 (beginner)

For few years I've been posting C# puzzles here, each puzzle was about a language feature or an unexpected semantics of some base class library methods. This post starts a new series, Javascript puzzles. Here's the first, easy one. Consider following generator function
function* foo()
{
    var n = 0;
    while ( true ) {
        yield n++;
    }
}
This seemingly creates an infinite enumeration of 0, 1, 2, etc. However, a simple test
for ( var i=0; i<10; i++ )
{
    console.log( foo().next().value );
}
reveals it doesn't really do what it's supposed to
0
0
0
0
0
0
0
0
0
0
The question here is to explain the incorrect behavior of the generator.

1 comment:

Tomek said...

Generator method is fine, however, the usage is wrong. Calling the foo() create a new generator on every call. So in order to keep the state of generator, we have to store it in a variable and then start iterating

var iter = foo()
for ( var i=0; i<10; i++ )
{
console.log( iter.next().value );
}