如何使用ramda.js让这段代码可读性最高?
发布于 4 年前 作者 guokangf 4335 次浏览 来自 问答
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 回复
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)]
    ]),
    []
)

不可读

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

来个不严谨的写法🙈

const childrenStr = JSON.stringify(children);
const ret = childrenStr.match(/\d+/g) || [];

@abiuDoIT 这解法 🐂 🐄 🐮

难道不是一句话的事吗?

children.flatMap(item => item?.props?.children || item).filter(i => i != null)

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

@Shonke node的最新版本吗?

回到顶部