JS Generator – Fibonacci Example
function fibonacci() { var i1 = 0, i2 = 1; while (true) { yield i1; var t = i1; i1 = i2; i2 += t; } } var g = fibonacci(); for (var i = 0; i < 10; i++) { document.write(g.next() + "\n"); }
The function fibonacci
contains the keyword “yield” making the function a generator. When the function is called it returns an iterator. The first time the iterator’s next function is called the fibonacci function runs like normal until the yield keyword. Yield works just like return, returning the value specified. The next time “next” is called the function continues on the first statement after the yield. In this example, the while loop adjusts the variables and yields the new value. After that, every time the next function is called it continues to rerun the same looping code, each time yielding the next value in the Fibonacci sequence.
When the generator function ends, instead of yielding then the generator is complete. The Fibonacci example never ends. But a simple addition can give the function an ending point.
function fibonacci(limit) { var i1 = 0, i2 = 1; while (true) { if (limit > 0) yield i1; else break; limit--; var t = i1; i1 = i2; i2 += t; } } var g = fibonacci(15); for (var i in g) { document.write(i + "\n"); }
In this manner, where you know the generator will end, the for in syntax works well.
NOTE: in Firefox the yield keyword doesn’t exist unless the script tag loading the function has a type of “text/javascript;version=1.7”. version must be 1.7 or higher.