ramda.js

Ramda: How to use R.map with two arguments?


It works fine with a pair of array. I don't need to use Ramda in this example.

const addChild1 =  (x , y) => `${x}.addChild(${y}); ` 
const result1 = addChild(["containerA"], ["a1","a2", "a3"])

console.log(result1) //containerA.addChild(a1,a2,a3) 

I couldn't make it work with 2d matrix of strings. I used R.map, but I get 'undefined' in the second argument.

const addChild2 =  R.map ((x , y) => `${x}.addChild(${y}); `) 
const result2 = addChild2(["containerA", "containerB", "containerC"], [["a1","a2", "a3"], ["b1","b2", "b3"], ["c1","c2", "c3"]])

console.log(result2) //["containerA.addChild(undefined); ","containerB.addChild(undefined); ","containerC.addChild(undefined); "]

How can I avoid the 'undefined'? Desirable output is the below :

["containerA.addChild("a1","a2", "a3"); ","containerB.addChild("b1","b2", "b3"); ","containerC.addChild("c1","c2", "c3");"]


Solution

  • R.map takes a functor (such as an array) as its second parameter, so in this case, only ["containerA", "containerB", "containerC"] got in the loop

    You should use R.zipWith in this case instead of map

    const addChild2 = R.zipWith((x, y) => `${x}.addChild(${y}); `)
    const result2 = addChild2(
      ["containerA", "containerB", "containerC"],
      [
        ["a1", "a2", "a3"],
        ["b1", "b2", "b3"],
        ["c1", "c2", "c3"],
      ]
    )
    
    console.log(result2)
    <script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>