2016-12-16 185 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