我正在学习函数式编程,如果有任何帮助我将不胜感激。使用ramda.js时,以下代码的功能等价物是什么?
const indexArray = (array)=>{
let idx = 0;
return array.map((l)=>{
return l.map((w)=>{
let nw = { id: idx, val: w }
idx++
return nw
})
})
}
indexArray([["Hello", "World"],["Foo", "Bar"]])
//=> [[{"id":0,"val":"Hello"},{"id":1,"val":"World"}],[{"id":2,"val":"Foo"},{"id":3,"val":"Bar"}]] 发布于 2017-09-30 13:19:05
使用Scott的部分回答(谢谢!)和一个递归函数,我想出了下面的解决方案。然而,我不禁想,一定有更优雅的方式来做这件事。
const indexElements = R.pipe(R.flatten, R.addIndex(map)((val, idx) => ({idx, val})))
const lengths = R.map((l)=>l.length)
const rf = (output, input, indexes)=>{
if (indexes.length == 0) return output
let index = indexes[0]
return rf(
R.append(R.take(index,input), output),
R.drop(index, input),
R.drop(1, indexes)
)
}
const indexNestedArray = (arr)=>rf([], indexElements(arr), lengths(arr))
indexNestedArray([["Hello", "World"],["Foo", "Bar"]])
// => [[{"idx": 0, "val": "Hello"}, {"idx": 1, "val": "World"}], [{"idx": 2, "val": "Foo"}, {"idx": 3, "val": "Bar"}]]https://stackoverflow.com/questions/46485065
复制相似问题