yield from a list of generators created from an array

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

I\'ve got this recursive generator

5条回答
  •  醉话见心
    2020-12-03 21:50

    The map is a good idea, but you need to reduce the resulting array of generator objects to just one generator object:

    function *flat(x) {
        if (Array.isArray(x)) 
            yield *x.map(flat).reduce((a, b) => function*() { yield *a; yield *b }());
        else
            yield 'foo' + x;
    }
    
    var obj = [1,2,3,[4,5,[6,7,8],9],10];
    console.log([...flat(obj)]);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题