我有数据的阵列将被转换成一个字符串。我创建了功能做变换。我的问题是什么是写这个功能,使其更具可读性的最佳方式?我不想有多个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?
我只想做这样的事情:
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
是一个简化if-else
,除非谓词返回true,它返回原来的值,在这种情况下,它首先应用变换函数。 (when
是相似的,除了它应用于改造时,谓语是真实的。)所以这个进行两个步骤,首先都转换成统一的格式,普通的字符串,然后将它们结合起来。
这可能会读更好的给你,但它们是完全等价的:
const transform = pipe(
map(unless(is(String), prop('name'))),
join(' '),
)
您可以使用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>
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}`
}, '')