Ramda — R.add
You may think to yourself, “Self, why do I need a function to add numbers?”. You might respond to yourself, “Good question”. Once you finish that conversation I will point to a few reasons in this post.
1+2 // 3
Seems simple right? It is.
R.add does the same thing.
R.add(1,2) // 3
Not only is it longer, but it’s a whole library to add 2 numbers. In simple contexts using
R.add may cause more confusion than it clears up. Here are a things that the
+ operator can’t do without it’s
Suppose we have a list of numbers that we want to sum. There are ways to do it with a
for loop and some
+ but I present a different way and a reason to use
let numbers = [1,2,3,4,5,6,7,8];
let sum = numbers.reduce(R.add, 0);
This assumes that you know how `reduce` works. If not, the usual use is: reduce takes a list of many things and turns it into fewer things (there are other uses). In this case we want to add every number with the previous sum.
We can also take advantage of the fact that
R.add is curried.
const shipping_and_handling = 19.99;
const make_money = R.add(shipping_and_handling);
const gadget = 3;
const gizmo = 2;
const one_easy_payment = R.add(make_money(gadget), make_money(gizmo));
One last thing I like about this function is that is explicitly casts to numbers so you won’t get some array concatenation shenanigans.