简体   繁体   中英

How to use nested functions as generator in javascript (using “inner” yields)

<script>
function * d1 (p)  {
    p-=1;
    yield p;
    p-=2;
    yield p;
}

var g=d1 (9);
var h;
console.log((h=g.next()).value+','+h.done+';');
console.log((h=g.next()).value+','+h.done+';');
console.log((h=g.next()).value+','+h.done+';');
</script>

gives 8,false; then 6,false; then undefined,true; whereas

<script>
function * d2 (p)     {
    function * d1 (p)     {
        p -=1 ;
        yield p;
        p -=2 ;
        yield p;
    }
    d1(p);
}
var g=d2 (9);
var h;
console.log((h=g.next()).value+','+h.done+';');
console.log((h=g.next()).value+','+h.done+';');
console.log((h=g.next()).value+','+h.done+';');
</script>

gives me three times undefined,true;

As I want the hidden structure of d1 (as inner-function), how can I proceed to still have the same result as on the first sample?

The d2 generator function doesn't yield nor return anything, so you only get undefined.

You probably want to call it passing p argument, and yield each iterated value with yield* .

function * d2 (p) {
  yield* function * d1 (p) {
    p -= 1;
    yield p;
    p -= 2;
    yield p;
  }(p);
}

For copy and past needs: that is the solution of Oriol working for me

<script>
function * d2 (p)     {
    function * d1 (p)     {
        p -=1 ;
        yield p;
        p -=2 ;
        yield p;          }
    yield * d1(p);    }
 // ^^^^^^^^ are the changes
var g=d2 (9);
var h;
console.log((h=g.next()).value+','+h.done+';');
console.log((h=g.next()).value+','+h.done+';');
console.log((h=g.next()).value+','+h.done+';');
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM