【问题标题】:Ramda pipe with multiple arguments具有多个参数的 Ramda 管道
【发布时间】:2016-12-20 00:36:14
【问题描述】:

我有一个需要多个参数的方法,我正在尝试设置一个 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 加载到 ramda repl 中的上述代码的链接。

【问题讨论】:

    标签: javascript ramda.js


    【解决方案1】:

    一种可能被重写的方式:

    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 的匿名函数替换为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]
    )
    

    【讨论】:

      【解决方案2】:

      我认为使用pluckprop 而不是path 可以提高可读性。像这样:

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

      当然,最好为函数使用一个好听的名称。喜欢getAttachedValueByNumber

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-04
        • 1970-01-01
        • 2020-04-27
        • 2017-10-12
        • 1970-01-01
        • 1970-01-01
        • 2018-06-01
        • 2016-08-17
        相关资源
        最近更新 更多