yield from a list of generators created from an array

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

I\'ve got this recursive generator

5条回答
  •  情话喂你
    2020-12-03 21:48

    You could use rest parameters ... and check the length of the rest array for another calling of the generator

    function* flat(a, ...r) {
        if (Array.isArray(a)) {
            yield* flat(...a);
        } else {
            yield 'foo' + a;
        }
        if (r.length) {
            yield* flat(...r);
        }
    }
    
    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; }

    A similar approach but with a spread generator for calling the handed over generator with the spreaded values.

    function* spread(g, a, ...r) {
        yield* g(a);
        if (r.length) {
            yield* spread(g, ...r);
        }
    }
    
    function* flat(a) {
        if (Array.isArray(a)) {
            yield* spread(flat, ...a);
        } else {
            yield 'foo' + a;
        }
    }
    
    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; }

提交回复
热议问题