実行を一時停止・再開できる関数。イテレータの実装に使われる
// ── ジェネレーター: 途中で一時停止できる特殊な関数 ──────
// function* と yield を使う
function* countUp(start = 0) {
let n = start;
while (true) {
yield n++; // yield: ここで一時停止して値を返す
// 次に next() が呼ばれるとここから再開する
}
}
const counter = countUp(1); // ジェネレーターオブジェクトを作成
console.log(counter.next().value); // 1 ← 最初の yield
console.log(counter.next().value); // 2 ← 2回目の yield
console.log(counter.next().value); // 3 ← 3回目の yield
// ── for...of で繰り返せる ────────────────────────────
function* range(start: number, end: number) {
for (let i = start; i <= end; i++) {
yield i; // start から end までの値を1つずつ返す
}
}
for (const num of range(1, 5)) {
console.log(num); // 1, 2, 3, 4, 5
}
// ── 実用的な使い方: 無限リストの遅延評価 ────────────
// メモリを節約しながら大量のデータを処理できる
function* fibonacci() {
let [a, b] = [0, 1];
while (true) {
yield a;
[a, b] = [b, a + b]; // フィボナッチ数列: 0,1,1,2,3,5,8,...
}
}無限シーケンスや遅延評価に有用。async/awaitの基盤技術でもある。for...ofや配列スプレッドで消費できる。