[英]combine functions in ramda
I have a function which takes two arguments, I want to curry it because it used more that one time in code.我有一个带有两个参数的函数,我想对其进行柯里化,因为它在代码中使用了不止一次。 here is the function :
这是功能:
const discount = R.sum(R.map(R.propOr('0', 'discount'), invoiceArr));
now I want to give argument's (' discount
' & invoiceArr
) and return the value.现在我想给出参数的 ('
discount
' & invoiceArr
) 并返回值。 I have try another way which like below:我尝试了另一种方式,如下所示:
const sumByPropName = R.curryN(2, R.compose(R.sum, R.pluck));
but this way has not propOr
method.但是这种方式没有
propOr
方法。
There's a number of ways you can go about this.有很多方法可以解决这个问题。 Assuming you still want the function curried, the easiest way is to just make add the arguments
假设您仍然希望函数柯里化,最简单的方法是添加参数
const sumByPropName = R.curry((prop, items) => R.compose(R.sum, R.map(R.propOr(0, prop)))(items))
An alternative is to use R.defaultTo
to map over the undefined values and set them all to 0
, before passing to sum
另一种方法是使用
R.defaultTo
映射未定义的值并将它们全部设置为0
,然后R.defaultTo
sum
const sumByPropName = R.curryN(2, R.compose(R.sum, R.map(R.defaultTo(0)), R.pluck))
Lastly, you could create a pluckOr
function yourself, keeping sumByPropName
a bit cleaner (although there's surely a nicer way to write pluckOr
)最后,您可以自己创建一个
pluckOr
函数,使sumByPropName
更sumByPropName
一些(尽管肯定有更好的编写pluckOr
)
const pluckOr = R.curry((defaultVal, propName, items) => R.map(R.propOr(defaultVal, propName), items))
const sumByPropName = R.curryN(2, R.compose(R.sum, pluckOr(0)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.