Skip to content

Instantly share code, notes, and snippets.

@YNSTakeru
Created March 17, 2024 19:29
Show Gist options
  • Save YNSTakeru/959fa2b7ebad83d3bc93d53d17e53149 to your computer and use it in GitHub Desktop.
Save YNSTakeru/959fa2b7ebad83d3bc93d53d17e53149 to your computer and use it in GitHub Desktop.
note generator question 1

問題1 ヒント

そもそもGenerator Functionがわからん
function* firstGenerator(X){
    while(true){
        yield X;
        ++X * 2;
    }
}

Generator Functionを扱う際は、functionの後に*が必要です。また、yieldは後述するnext()が呼び出された際の返却値が入ります。

Generator Functionの呼び出し方

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}

引数が0Generator Functionを実行してfirstGenという変数に格納します。firstGen.next()を実行することで、yield X;まで実行されます。yieldは通常のFunctionreturnのような役割です。yieldreturnと異なる点は、再度firstGen.next()が実行された際、yield X;が実行された直後の++X * 2;から実行される点です。加算が終わった後、while(true)によってyield X;まで戻ってきて返却値を返します。

問題1 解答

クリックして開く
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*と記述する必要があります><

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment