Java Reference
In-Depth Information
To define a generator function, an asterisk symbol ( * ) is placed after the function declara-
tion, like so:
function* exampleGenerator() {
}
Calling a generator function doesn't actually run any of the code in the function; it returns
a new generator object. This can then be used to implement an iterator. For example, we
can create a generator to produce a Fibonacci-style number series (a sequence that starts
with two numbers and the next number is obtained by adding the two previous numbers
together) using the following code:
function* fibonacci(a,b) {
let [ prev,current ] = [ a,b ];
for (;;) {
[prev, current] = [current, prev + current];
yield current;
}
}
The code starts by initializing an array with the first two values of the sequence, which
are provided as arguments to the function. A for loop is then used without any conditions
(hence the ;; inside the parentheses) as none are needed; the loop will continue indefin-
itely every time the iterator's next() method is called. Inside this loop is where the next
value is calculated by adding the previous two values together.
Generator functions employ the special yield keyword that is used to return a value. The
difference between the yield and the return keywords is that by using yield , the
state of the value returned is remembered the next time yield is called. Hence, the current
value in the Fibonacci sequence will be stored for use later.
To create a generator object based on this function, we simply assign a variable to the func-
tion:
let sequence = fibonacci(1,1);
Search WWH ::




Custom Search