2016-12-16 62 views
0

我有一个需要多个参数的方法,我试图设置一个ramda管道来处理它。具有多个参数的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中。这也可能会被改写

回答

2

方式一:

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.find代替R.pathEq。一旦找到,可以通过使用R.path走下对象的属性来检索该值。

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

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

我觉得可读性可以用pluckprop代替path得到改善。像这样:

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

当然,最好使用一个好名字的函数。像getAttachedValueByNumber