yield from a list of generators created from an array

后端 未结 5 1256
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 21:13

I\'ve got this recursive generator

5条回答
  •  广开言路
    2020-12-03 22:06

    You could reduce array to generator. But this looks worse than for loop to me (though is functional :) )

    var obj = [1, 2, 3, [4, 5, [6, 7, 8], 9], 10]
    
    function* flat(x) {
      if (Array.isArray(x))
        yield * x.reduceRight(
          (f, y) => function*() {
            yield * flat(y);
            yield * f()
          },
          function*() {}
        )()
      else
        yield 'foo' + x;
    
    }
    
    console.log([...flat(obj)])

提交回复
热议问题