如何使用ramda.js让这段代码可读性最高

const isObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]';
function toArray1(children) {
    const ret = children.reduce(
        (acc, cur) => {
            if (cur === null) return acc;
            if (Array.isArray(cur)) {
                acc = acc.concat(toArray1(cur));
            } else if (isObject(cur) && cur.props) {
                acc = acc.concat(toArray1(cur.props.children));
            } else {
                acc.push(cur);
            }
            return acc;
        },
        []
    );

    return ret;
}
const children = [
    1,
    null,
    [2, 3],
    {
        props: {
            children: [4, 5]
        }
    }
];
const ret = toArray1(children);
console.log(ret);

输出结果:[1, 2, 3, 4, 5]

阅读 319
评论
    2 个回答
    const children = [
        1,
        null,
        [2, 3],
        {
            props: {
                children: [4, 5]
            }
        }
    ]
    const result = children.filter(o=>o!==null).flatMap(o=>o.props?o.props.children:o)
    console.log(result)

    这样你看可以嘛?

      • 886

      等待函数式玩的熟悉的同学指导一二呀

      经过各种尝试现在改成:

      const handleRecuce = (acc, cur) =>
          R.cond([
              [
                  R.and(R.is(Object), R.has('props')),
                  R.compose(R.concat(acc), R.prop('children'), R.prop('props'))
              ],
              [R.is(Array), R.concat(acc)],
              [R.T, R.flip(R.append)(acc)]
          ])(cur);
      const toArray = R.compose(R.reduce(handleRecuce, []), R.filter(R.compose(R.not, R.isNil)));

      如何在这里面使用递归还没研究出来
      有研究的更深入的大佬,再给指导指导呀

        撰写回答

        登录后参与交流、获取后续更新提醒

        相似问题
        推荐文章