Confused about javascript generator function -


why value of final b not 24 18?
think when function s2 called last time, a 12 , last 2, b should equal 12 * 2 = 24.

let = 1, b = 2;    function* foo() {    a++;    yield;    b = b * a;    = (yield b) + 3;  }    function* bar() {    b--;    yield;    = (yield 8) + b;    b = * (yield 2);  }    function step(gen) {    let = gen();    let last;      return function () {      last = it.next(last).value;    };  }    let s1 = step(foo);  let s2 = step(bar);    s2(); //b=1 last=undefined    s2(); //last=8    s1(); //a=2 last=undefined    s2(); //a=9 last=2    s1(); //b=9 last=9    s1(); //a=12    s2(); //b=24    console.log(a, b);

in last line of bar function:

b = * (yield 2); 

the code ran a * before running (yield 2). seem a evaluated @ point.

if move multiplication a after (yield 2), seems a evaluated after (yield 2) run, thereby ensuring date value of a.

so last line of bar function become:

b = (yield 2) * a; 

this can seen in example below.

let = 1, b = 2;    function* foo() {    a++;    yield;    b = b * a;    = (yield b) + 3;  }    function* bar() {    b--;    yield;    = (yield 8) + b;    b = (yield 2) * a;  }    function step(gen) {    let = gen();    let last;      return function () {      last = it.next(last).value;    };  }    let s1 = step(foo);  let s2 = step(bar);    s2(); //b=1 last=undefined    s2(); //last=8    s1(); //a=2 last=undefined    s2(); //a=9 last=2    s1(); //b=9 last=9    s1(); //a=12    s2(); //b=24    console.log(a, b);


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -