ramda js 使用 reduce 连接值

ramda js concat the value using reduce

我有一组数据将被转换成字符串。我已经创建了进行转换的功能。我的问题是编写此函数以使其更具可读性的最佳方式是什么?我不想有多个 if/else 语句。

const data = [
    "hello",
    {name: "Bob"},
    "and",
    {name: "Fred"},
    "How are you guys today?",
]

const isString = R.is(String)
const isObject = R.is(Object)

const getName = R.prop('name')

const toPureString = R.reduce(
    (result, value) => {
        if (isString(value)) {
            return `${result}${value} `
        }
        if (isObject(value)) {
            return `${result}${getName(value)}`
        } 
        return result
    }, "")

toPureString(data)
// hello Bob and Fred How are you guys today?

Ramda 有一个 ifElse 函数。但是,当您的 if 语句有多个分支时,它会变得笨拙:

const ifStr = R.ifElse(isString, v => `{result}{v}`, () => result);
return R.ifElse(isObject, v => `{result}{getName(v)}`, ifStr);

对于那种情况,我会用普通的三元语句来完成 JavaScript:

const toPureString = R.reduce((result, value) => {
    const str = isObject(value) ? getName(value) : (isString(value) ? value : '')
    return `${result}${str}`
}, '')

您可以使用 R.cond:

const { flip, is, unapply, join, useWith, prop, T, identity } = R

const isString = flip(is(String))
const isObject = flip(is(Object))
const spacer = unapply(join(' '))
const getName = useWith(spacer, [identity, prop('name')])

const toPureString = R.reduce(R.cond([
  [isString, spacer],
  [isObject, getName],
  [T, identity]
]), '')

const data = [
    "hello",
    {name: "Bob"},
    "and",
    {name: "Fred"},
    "How are you guys today?",
]

const result = toPureString(data)

console.log(result) // hello Bob and Fred How are you guys today?
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>

我会做这样的事情:

const {compose, join, map, unless, is, prop} = R
const data = ['hello', {name: 'Bob'}, 'and', {name: 'Fred'}, 'How are you guys today?']

const transform = compose(join(' '), map(unless(is(String), prop('name'))))

console.log(transform(data))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>

unless is a simplified if-else, which returns the original value unless the predicate returns true, in which case it applies the transformation function first. (when 类似,只是它在 谓词为真时应用转换 。)所以这分两步进行,首先将所有内容转换为一致的格式,纯字符串,然后组合它们。

这对您来说可能更好读,但它们是完全等价的:

const transform = pipe(
  map(unless(is(String), prop('name'))),
  join(' '), 
)