そもそもGenerator Functionがわからん
function* firstGenerator(X){
while(true){
yield X;
++X * 2;
}
}
Generator Function
を扱う際は、function
の後に*
が必要です。また、yield
は後述するnext()
が呼び出された際の返却値が入ります。
const firstGen = firstGenerator(0)
console.log(firstGen.next()) // {value: 0, done: false}
console.log(firstGen.next()) // {value: 2, done: false}
console.log(firstGen.next()) // {value: 6, done: false}
引数が0
のGenerator Function
を実行してfirstGen
という変数に格納します。firstGen.next()
を実行することで、yield X;
まで実行されます。yield
は通常のFunction
のreturn
のような役割です。yield
がreturn
と異なる点は、再度firstGen.next()
が実行された際、yield X;
が実行された直後の++X * 2;
から実行される点です。加算が終わった後、while(true)
によってyield X;
まで戻ってきて返却値を返します。
クリックして開く
function* firstGenerator(x) {
let index = 0;
while (true) {
yield x[index];
++index;
}
}
const firstGen = firstGenerator(lines);
let output = firstGen.next().value;
while (output) {
console.log(output);
output = firstGen.next().value;
}
Generator Function
の内部でGenerator Function
を呼ぶには一工夫必要です><
function* secondGenerator(x) {
yield x;
}
function* firstGenerator(x) {
let index = 0;
yield* secondGenerator(x);
while (true) {
yield x[index];
++index;
}
}
また、`Arrow Function`は`yield`は使えません><
上記のようにGenerator Function
内部でGenerator Function
を呼び出すにはyield*
と記述する必要があります><