我正在学习函数式编程,并希望得到任何帮助。以下代码的功能等价物将使用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"}]]
答案 0 :(得分:0)
使用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"}]]