[英]Index nested list using ramda.js
I'm learning functional programming and would appreciate any help. 我正在学习函数式编程,希望对您有所帮助。 What would the functional equivalent of the following code be using ramda.js?
使用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"}]]
Using Scott's partial answer (thanks!) and a recursive function, I came up with the following solution. 使用Scott的部分答案(谢谢!)和递归函数,我提出了以下解决方案。 I can't help thinking there must be a more elegant way to do it, though.
不过,我不禁要想到必须有一种更优雅的方法。
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"}]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.