Adam Johnston

Ramda Add

https://ramdajs.com/docs/#add

Ramda is full of useful functions and add is the first in the list. It helps by being one of the most simple functions (there are others that are even smaller). The aim of these little posts are to visit each function at a time and better understand how it is written and why it is useful.

Add is one of the more straightforward functions in Ramda. It is used to add two numbers together. Like all functions in Ramda it is automagically curried and and can be written in few ways. You can pass a single value and create a whole new function, pass both arguments to get a new value or call add twice with a single argument each time to get a value. Take a look below for some examples:

const add2 = add(2) // (x) => y
const sumA = add(2, 2) // 4
const sumB = add(2)(2) // 4

Example use-cases

Add a standard fee to a product price:

const bookingFee = 1.99
const calculateTotal = add(bookingFee)
const total = calculateTotal(19.99) // 21.98

A ticket for every time someone joins a queue:

const increment = add(1)
const peopleQueueing = 12
const takeTicket = (peopleQueuing) => increment(peopleQueuing)
const yourNumber = takeTicket(peopleInQueue) // 13

How to write your own

You can always check out Ramda’s implementation but they have an entire library to work with and writing your own you might not have those benefits. Since I am doing this as a process for learning we’ll take a look at a simple implementation and then a curried version.

Simple

The simple version of add will be a function that takes two arguments and adds those numbers together.

// es6
const add = (x, y) => x + y

// es5
function add(x, y) {
  return x + y
}

// TS
const add = (x: number, y: number): number => x + y

Curried

The curried version is very similar to the above. If you don’t know what currying is there is a chapter on currying in the Mostly Adequate Guide to Functional Programming book. If you prefer short videos then FunFunFunction’s episode on currying is worth a watch.

// es6
const add = (x) => (y) => x + y

// es5
function add(x) {
  return function add(y) {
    return x + y
  }
}

// TS
const add =
  (x: number) =>
  (y: number): number =>
    x + y