The most boring generator function's caller

EcmaScript6 generator that does nothing

While generator functions are great (see my other EcmaScript6 posts), it is up to the caller function to take advantage. For example, the caller function might do nothing!

Presenting the most boring caller function passValue that just passes the value back to the generator.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function *one() {
var k = yield 1;
console.log('k =', k);
}
function passValue(generator) {
var result, x;
while (true) {
result = generator.next(x);
if (result.done) break;
x = result.value;
}
}
var gen = one();
passValue(gen);
// run using node v0.11 and --harmony flag
// prints: k = 1

One can remove the wildcard in front of *one, remove yield and use the function directly, there is no difference.