taquaki-satwo
11/27/2017 - 3:07 PM

ジェネレータに値を渡す

JS-ジェネレータに値を渡す

function* fibonacci() {
  let fn1 =0, fn2 = 1, fnew, reset;
  while(true) {
    const fnew = fn1 + fn2;
    fn1 = fn2;
    fn2 = fnew;
    reset = yield fn1;
    if(reset) {
      fn1 = 0;
      fn2 = 1;
    }
  }
}

var iter = fibonacci();
for(let i=0; i<10; i++) {
  console.log(iter.next().value);
}

console.log(iter.next().value);
console.log(iter.next(true).value);
console.log(iter.next().value);
console.log(iter.next().value);

// return()でイテレータを終了する
console.log(iter.return());
console.log(iter.next());

JS-ジェネレータに値を渡す

A Pen by Takaaki Sato on CodePen.

License.