2017-02-19 110 views
1

我想最近學習fp,並嘗試使用ramda.js到我的項目,但我遇到了一些問題。與ramda.js代碼有什麼不同?

我的代碼的目標是我想將result prop添加一些初始值到list數組的每個元素中,但它沒有按預期工作。

這裏是我的代碼:

var list = [{name: 'foo'}, {name: 'bar'}, {name: 'baz'}] 
 
var list1 = R.clone(list) 
 

 
var getResultList = R.times(R.identity) 
 

 
// what's the difference between them ?? 
 
// it worked as expected if I wrap assoc fn into arrow function and transfer it to fn 
 
var mapAssocResult= R.map(e=> R.assoc('result', getResultList(2), e)) 
 
// it didn't work as expected if I just transfer it as param of map fn 
 
var mapAssocResult1= R.map(R.assoc('result', getResultList(2))) 
 

 
list = mapAssocResult(list) 
 
list1 = mapAssocResult1(list1) 
 

 
list[0].result === list[1].result //false 
 
list1[0].result === list1[1].result // true 
 
// it seems that all result props point to the same array reference, but why?

是不是我需要使用Ramda.js注意?

也許我在使用Ramda.js的想法是完全錯誤的,那麼是否有更合理的方法來實現我在Ramda.js中的目標?

非常感謝。

+0

我並沒有超出斯科特克里斯托弗下面的建議,但我會注意到'R.range(0)'可能更具描述性,並且肯定比'R.times(R.identity)'更簡潔。 –

+0

感謝您的建議。 –

回答

1

您看到的結果是由於getResultList(2)R.map(R.assoc('result', getResultList(2)))中過早評估所致。這最終相當於R.map(R.assoc('result', [0, 1])),它將爲每個元素的result屬性分配相同的[0, 1]實例。

額外的箭頭功能防止了評估,直到映射函數被施加到所述陣列的每個元素,從而導致[0, 1]每個result屬性一個新的和唯一的實例getResultList(2)

+0

非常感謝,順便說一下,在Ramda.js中有更合理的方式來實現我的目標嗎?因爲我注意到關於ramda.js的文章的例子總是使用無點式的風格來實現某些東西。 –

+0

免積分是一個很好的工具,可以幫助使某些代碼更具可讀性。但不要迷戀它。如果我們想出了這個免費的版本,它可能會變得非常不可讀。所以這裏不值得。 –