从数组创建的生成器列表中获取 [英] yield from a list of generators created from an array

查看:155
本文介绍了从数组创建的生成器列表中获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个递归生成器

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)

这不起作用。

是否有为循环而不用编写上述函数的方法?

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

推荐答案

你可以使用休息参数 ... 并检查剩余数组的长度,以便再次调用生成器

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; }

类似的方法,但 spread 生成器,用于调用带有扩展值的移交生成器。

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; }

这篇关于从数组创建的生成器列表中获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆