Generators allow you to define an iterative algorithm by writing a single function that can maintain its own state. A generator is a special type of function that works like a factory for iterators. A function becomes a generator if it contains one or more output expressions. When calling the generator function, the function body is not executed immediately; instead, it returns an iterator-generator object. Each call to the generator-iterator next () method executes the function body until the next yield expression and returns its result. When either the end of the function or the return statement is reached, a StopIteration exception is thrown. The generator function can be used directly as a class iterator method, which significantly reduces the amount of code required to create custom iterators.
function Range(low, high){ this.low = low; this.high = high; } Range.prototype.__iterator__ = function(){ for (var i = this.low; i <= this.high; i++) yield i; }; var range = new Range(3, 5); for (var i in range) print(i);
Not all generators end; You can create a generator that represents an infinite sequence.
user-s
source share