LoginSignup
0
1

More than 1 year has passed since last update.

【JavaScript】イテレーターとジェネレーター

Last updated at Posted at 2023-05-25

イテレーター

反復操作を行う際に使用するオブジェクト
valuedoneのプロパティを持つオブジェクトを返す next() メソッドを持つことによってイテレータープロトコルを実装するオブジェクト

value

反復シーケンスの次の値

done

シーケンスの最後の値が既に消費されている場合に true となります
done と並んで value が存在する場合、それがイテレーターの戻り値となります

記述ルール

.js
function genIterator() {
  return {               // 戻り値のオブジェクトの部分がイテレータ
    next: function() {
        return {
          done: false / true, // ループを継続するかどうか
          value:            // ループ時に渡ってくる値を格納
        }
      }
  }
}

Example

Example.js
function makeRangeIterator(start = 0, end = Infinity, step = 1) {
    let nextIndex = start;
    let iterationCount = 0;

    const rangeIterator = {
       next: function() {
           let result;
           if (nextIndex < end) {
               result = { value: nextIndex, done: false }
               nextIndex += step;
               iterationCount++;
               return result;
           }
           return { value: iterationCount, done: true }
       }
    };
    return rangeIterator;
}

const it = makeRangeIterator(1, 10, 2);

let result = it.next();
while (!result.done) {
 console.log(result.value); // 1 3 5 7 9
 result = it.next();
}

console.log("Iterated over sequence of size: ", result.value); // [5 numbers returned, that took interval in between: 0 to 10]

ジェネレーター

イテレータを生成するための特殊な関数
ジェネレーター関数はfunction*という構文を使って定義され、複数の値を生成することができる

.js
function* gen() {
  if (ループが継続なら) {
    yield ; // yieldはイテレーターのオブジェクトを指す (done: false, value:値)
  } else {
    return ;
}

イテレーターとジェネレーター

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1