带有多个参数的 Ramda 管道 [英] Ramda pipe with multiple arguments

查看:34
本文介绍了带有多个参数的 Ramda 管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a method which requires multiple arguments, and I am trying to set up a ramda pipe to handle it.

这是一个例子:

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) ?

Is there a cleaner way of doing this, especially the x => x.number === number part of filter and having to call (array) at the end of the pipe?

这里是 上面代码的链接加载到 ramd一个副本.

Here's a link to the code above loaded into the 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 遍历对象的属性来检索该值.

Here we've replaced the use of R.pluck and the anonymous function given to R.find with R.pathEq given as the predicate to R.find instead. Once found, the value can be retrieved by walking down the properties of the object with R.path.

可以使用 R.useWith 以无点的方式重写此代码,但我觉得在此过程中会丢失可读性.

It is possible to rewrite this in a point-free manner using R.useWith, though I feel readability gets lost in the process.

const method = R.useWith(
  R.pipe(R.find, R.path(['data', 'attached', 0])),
  [R.pathEq(['data', 'number']), R.identity]
)

这篇关于带有多个参数的 Ramda 管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆