Currying

Photo by Caroline Attwood on Unsplash

Is a technique for converting function calls with N arguments into chains of N function calls with a single argument for each function call?

Currying always returns another function with only one argument until all of the arguments have been applied. So, we just keep calling the returned function until we’ve exhausted all the arguments and the final value gets returned.

// Normal function

function addition(x, y) {

return x + y;

} // Curried function

function addition(x) {

return function(y) {

return x + y;

}

}

Note: Curry takes a binary function and returns a unary function that returns a unary function. Its JavaScript code is

function curry(f) {

return function(x) {

return function(y) {

return f(x, y);

}

}

}

Note: A curried functions have a built-in iterator behaviour. One argument is applied at once which is then returned to the calling function to be used for next step. Read here about iterators.

Usages

The common use-case for curried function are function composition.e.g., p(x) = q(r(x)) . i.e building the new function from old function by passing arguments. Function q takes the return value as an argument from function r . Since a function can only return one value, the function being applied to the return value must be unary. Curried function can also be used while infrastructure setup of a project where there is a lot of possibilities to create generic functions thereby little pieces can be configured and reused with ease, without clutter. Ramda.js lib. functions are automatically curried and lodash has a function called curry which can be used to form curry function. Memoization is another good use case for curry function. Handling error throwing functions and exiting immediately after an error. Catching multiple error and use it as a validator on API’s and client side code. Can create First class functions which means that we can use functions as arguments and return values. Eg:

const func1 = () => console.log ('Hey Medium.');

const firstClassfunc1 = argsFunc => argsFunc();

const firstClassfunc2 = () => func1;

firstClassfunc1 (firstClassfunc2()); // Hey Medium.

Note: Do go through this video and you know more about why, when and usage.

Curry Factory Method(ES6)

const compose = (...fns) =>

fns.reduce((f, g) => (...args) => f(g(...args)));

Here is a good article on how to make our own curry function factory method using ES5.