yield from a list of generators created from an array

Viewed 4112

I've got this recursive generator

var obj = [1,2,3,[4,5,[6,7,8],9],10]

function *flat(x) {
    if (Array.isArray(x))
        for (let y of x)
            yield *flat(y)
    else
        yield 'foo' + x;

}

console.log([...flat(obj)])

It works fine, but I don't like the for part. Is there a way to write it functionally? I tried

if (Array.isArray(x))
   yield *x.map(flat)

which didn't work.

Is there a way to write the above function without for loops?

5 Answers
Related