I'm learning functional programming and would appreciate any help. What would the functional equivalent of the following code be using 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. 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"}]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.