具有多个参数的 Ramda 管道

Ramda pipe with multiple arguments

我有一个需要多个参数的方法,我正在尝试设置一个 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)

是否有更简洁的方法来执行此操作,尤其是 filterx => x.number === number 部分并且必须在管道末端调用 (array)

Here's一个link把上面的代码加载到ramda repl.

一种可能重写的方式:

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

这里我们用 R.pathEq 代替了 R.pluck 的使用和给 R.find 的匿名函数,作为 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]
)

我认为使用 pluckprop 代替 path 可以提高可读性。像这样:

const method = R.useWith(
  R.pipe(R.find, R.prop('attached')),
  [R.propEq('number'), R.pluck('data')]
);

当然,最好为函数取一个好听的名字。喜欢 getAttachedValueByNumber.