Currying in Node.js


29 April 2015, by

Having been doing a lot of functional programming recently, I discovered myself wanting to curry functions while doing some work in Node.js recently, but the question arose as to how?
Currying a function is providing some of its parameters now, and the rest later and is very common in Functional languages:

Scala

def add(x:Int)(y:Int) = x + y
def add2 = add(2)
add2(10)     // 12

F#

let add x y = x + y
let add2 x = add 2
add2 10      // 12

But how can you do this in javascript when you have to provide all of the arguments to your function?
Well here are a few options:

  1. Get the extra variables in scope (not really the point, but will work in some situations).
    val y = 2;
    function add2(x) { return  x + y; }
    add2(10);    // 12
  2. Return a function from your function.
    function add(x) { return function(y) { return  x + y; }; }
    var add2 = add(2);
    add2(10);    // 12
  3. Use bind to perform partial application instead.
    var add = function(a, b) { return a + b; }
    var add2 = add.bind(null, 2);
    add2(10);    // 12
  4. Extend Function.protocol.
    Function.prototype.curry = function(){
      var slice = [].slice,
          args = slice.apply(arguments),
          that = this;
      return function() {
        return that.apply(null, args.concat(slice.apply(arguments)));
      };
    };
    var add2 = add.curry(2);
    add2(10);    // 12
  5. Use the curry library.
    var curry = require('curry');
    
    var add = curry(function(a, b){ return a + b });
    var add2 = add(2);
    add2(10);    // 12

The curry library is doing something very close to 2 behind the scenes. It will however also let you do partial application as well if you want.

var sum = function(){
  var nums = [].slice.call(arguments);
  return nums.reduce(function(a, b){ return a + b });
}
var sum2 = curry.to(2, sum);
sum2(2)(10);      // 12

Tags: , , ,

Categories: Softwire, Technical

«
»

One Response to “Currying in Node.js”

  1. Sam Collard says:

    In addition to the above, there are curry and partial methods included in the lodash library, which your project may already be using (and provides a lot of other utility methods to make functional JS nicer).


Leave a Reply

* Mandatory fields


three + 5 =

Submit Comment