CNode

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

问答
Gguokangf发布于6 年前最后回复6 年前7 回复5261 浏览0 收藏
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);
查看回复

回复 (7)

Y
yviscool#1·6 年前
const { pipe, path, has, both,  concat, cond, T, identity, is,  reduce, append, isNil, flip,  useWith } = require('ramda')

const isNull = flip(isNil);
const isArray = flip(is(Array));
const isObjectAndHasProps = flip(both(is(Object), has('props')));

const toArray1 = reduce(
    cond([
        [isNull, identity],
        [isArray, useWith(concat, [identity, t => toArray1(t)])],
        [isObjectAndHasProps, useWith(concat, [identity, pipe(path(['props', 'children']), t => toArray1(t))])],
        [T, flip(append)]
    ]),
    []
)

不可读

A
abiuDoIT#2·6 年前

挺简单的逻辑为啥一定要用这些函数...

来个不严谨的写法🙈

const childrenStr = JSON.stringify(children);
const ret = childrenStr.match(/\d+/g) || [];
S
Shonke#4·6 年前

难道不是一句话的事吗?

children.flatMap(item => item?.props?.children || item).filter(i => i != null)
A
abiuDoIT#5·6 年前
引用 Shonke难道不是一句话的事吗?

@Shonke ?. 现在js 支持这写法了? 😳

参与回复
登录后即可参与回复。登录