Ramda — R.__
I was looking through the docs yesterday and decided that some of the docs are kinda dense. So, I want to walk through each function and use it. Maybe, I’ll do one a weekday. Hopefully, I can learn it and then explain it (maybe just a little). This will likely end up being something I don’t follow through on but I will try. I’ll start at the top and work down alphabetically.
The first one is
R.__. The docs say it’s a placeholder. I like to think of it like an I.O.U. from someone reputable. You take the I.O.U. as a substitute for what you really want but really you are just waiting for the money. In the same way we can use
R.__ as an I.O.U. for a curried function. The curried part is important and I know the ‘C’ is pretty far away so lets touch on that for a sec.
Currying is when we take a function that takes one or more parameters and we allow those parameters to be passed in over time instead of all at once. An example may help:
// not curried
const add = (a,b) => a+b;
add(1) // 1undefined
// cheap curry
const add = a => b => a+b;
add(1) // function
add(1)(2) // 3
My curry is a cheap curry but the concept is the same. We can pass in the first parameter at one point and we get a function back waiting for the next parameter. Once all parameters are passed in then we get the result.
This works out really well when the parameter order and the order that you have data available match. But, what do we do when it doesn’t?
Imagine a situation where your function takes multiple inputs and provides a single output. You need both inputs in order to get the output you desire. Unfortunately, your second input is available first. We need a way to pass in the second input and wait for the first.
const divide = R.curry((num, den) => num/den);
// will cause problems
divide()(3) // NaN
divide(R.__)(3) // function
divide(R.__)(3)(21) // 7
See! We gave our function an I.O.U and we made good on it. Once we did, we got our result. Until then, we get the creepy mouth breather function that quietly reminds us that we owe him something.
I find that I usually use this when I’m working with legacy functions that have odd parameter ordering. It allows me to bind parameters to the function when I’m ready and have them in scope. Then I just pass the bound function around! YAY!
Day 1 done.