A generator is a special type of function that works as a factory for
iterators and it allows you to define an iterative algorithm by writing a
single function which can maintain its own state. A function becomes a
generator if it contains one or more
yield statements.
When a generator function is called, the body of the function does not
execute straight away; instead, it returns a generator-iterator object.
Each call to the generator-iterator's next() method will execute the
body of the function up to the next
yield statement and return its result.
When either the end of the function or a return statement is reached,
a StopIteration exception is thrown.
For example, the following fib() function is a Fibonacci number generator,
that returns the generator when it encounters the
yield statement:
function fib() {
var fibNum = 0, j = 1;
while (true) {
yield fibNum;
var t = fibNum;
fibNum = j;
j += t;
}
}
To use the generator, simply call the next() method to access the values
returned by the function:
var gen = fib();
for (var i = 0; i < 10; i++) {
document.write(gen.next() " ");
}