具有多个参数的 Ramda 管道

2023-12-01

我有一个需要多个参数的方法,我正在尝试设置一个 ramda 管道来处理它。

这是一个例子:

const R = require('ramda');
const input = [
  { data: { number: 'v01', attached: [ 't01' ] } },
  { data: { number: 'v02', attached: [ 't02' ] } },
  { data: { number: 'v03', attached: [ 't03' ] } },
]

const method = R.curry((number, array) => {
  return R.pipe(
    R.pluck('data'),
    R.find(x => x.number === number),
    R.prop('attached'),
    R.head
  )(array)
})

method('v02', input)

有没有更干净的方法来做到这一点,特别是x => x.number === number部分filter并且必须打电话(array)在管道的末端?

Here's上面代码的链接已加载到 ramda repl 中。


可以重写的一种方法是:

const method = R.curry((number, array) => R.pipe(
  R.find(R.pathEq(['data', 'number'], number)),
  R.path(['data', 'attached', 0])
)(array))

这里我们替换了使用R.pluck以及赋予的匿名函数R.find with R.pathEq作为谓词给出R.find反而。找到后,可以通过使用以下命令遍历对象的属性来检索该值R.path.

可以使用无点方式重写它R.useWith,尽管我觉得可读性在这个过程中丢失了。

const method = R.useWith(
  R.pipe(R.find, R.path(['data', 'attached', 0])),
  [R.pathEq(['data', 'number']), R.identity]
)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

具有多个参数的 Ramda 管道 的相关文章

随机推荐