Currying

What is Currying?

Currying in javascript is a concept to transform multi parameter funtion to sequence of single parameter functions. It's used not only in JavaScript, but in other languages as well.

Currying translates a function from callable as f(a, b, c) into callable as f(a)(b)(c).


Example

Following is an example for currying 3 parametered sum function

function curry(f) { // curry(f) does the currying transform
return function(a) {
return function(b) {
  return function(c) {
    return f(a, b, c);
  };
};
};
}

// Following is a funtion with 3 parameter
function sum(a, b, c) {
return a + b + c;
}

let curriedSum = curry(sum); // returns a single argument funtion

alert(curriedSum(1)(2)(3)); // 6

Real world Example

Following is an example for currying 2 parametered tax calculation function. As different country have different taxes. Currying can be used to keep tax fixed based on country. For Instance: India tax = 30% US tax = 10%

function curry(f) { // curry(f) does the currying transform
return function(a) {
return function(b) {
  return f(a, b);
};
};
}

// Following is a funtion with 2 parameter
function calculateTax(tax, income) {
return income * tax / 100;
}

let curriedTax = curry(calculateTax); // returns a single argument funtion
let indiaTax = curriedTax(30); // returns a funtion to take 'income' parameter
let usTax = curriedTax(10); // returns a funtion to take 'income' parameter
alert(indiaTax(1000)); // 300
alert(usTax(1000)); // 100