Currying Functions

What tasty thing is this?

The process of converting a function that accepts multiple arguments, into one that accepts a single argument, by binding some of the arguments into the original function.

function multiply(op1, op2){
  return op1*op2;
}

var times5 = curry(multiply, 5);

var product = times5(4); // 20

Why Should we Curry?

To understand every function as taking

at most one argument.

 

To stay DRY when invoking functions that use the same arguments many times.

function tax(percent, amount){
  return Math.round(amount * percent)/100;
}
var taxOf110InHawaii = tax(4.712, 110); // 5.18

var hiTax = curry(tax, 4.712);
taxOf110InHawaii = hiTax(110); // 5.18

Manually Currying

Write a function that returns another function that accesses the argument of the original function.

The original function arguments change the result of the returned function when its invoked.

function add(op1){
  return function(op2){
    return op1 + op2;
  }
}

var add5 = add(5); // a function that adds 5

var sumOf5and4 = add5(4); // 9

var shortHand = add(5)(4); // 9

Using Curry Helper

Use a helper function to convert functions into a curried function that accepts a single argument.

function curry(fn) {
  var args = Array.prototype.slice.call(arguments, 1);
  return function () {
    return fn.apply(this, args.concat(
      Array.prototype.slice.call(arguments, 0)
    ));
  };
}

convert a function

function concat (head, tail){
  return head + tail;
}

var greet = curry(concat,'Hello ');

greet('Jason'); // Hello Jason

Currying Functions

By Joe Karlsson

Currying Functions

basic currying in javascript

  • 1,587