In an earlier post we looked at generator functions in JavaScript.
Generator methods can call into other generator methods, and yield values received from another generator method. A generator can even unroll or flatten another generator’s result into it’s own iterator using yield*. As an example, consider the following generator method which yields two strings.
let inner = function*() { yield "Hello"; yield "there"; }
The next generator will call the inner generator using the yield* syntax.
let outer = function*() { yield* inner(); yield "World"; }
The yield* syntax will flatten the result from inner so that the outer generator yields three strings.
var result = Array.from(outer()); expect(result).toEqual(["Hello", "there", "World"]);
If the outer generator used yield instead of yield*, the result of outer would be inner’s iterator, followed by the string “World”.