Tag Javascript

Javascript and Partially Applying Functions

Recently on hacker news an article called “The Four Cs of Javascript” was featured and it discussed four javascript features or patterns that started with C: closures, callbacks, cascading (chaining), and currying. The first 3 I am intimately familiar with and use, nearly, on a daily basis. The last, currying, I had never heard of, probably, because, as it turns out it doesn’t appear to be all that useful and second, the name “currying” is not really accurate. But I was still curious and wanted to understand what currying is.

What is Currying?

There is a fairly formal definition of currying at wikipedia, and it’s named after Haskell Curry. But, as it turns out, javascript currying is commonly defined as filling in some arguments of a function, which then returns a new function where the remaining arguments can be filled in.This design pattern is more accurately known as partially applying functions.

Partially Applying Functions

Partially applying functions is useful wherever you may need to remember state and can be demonstrated with a simple and contrived example:

function add(){
    var result = 0;
    for(var i=0, len=arguments.length; i<len; i++){
        result += arguments[i];
    }
    return result;
}
 
function partial(fn){
    var partial_args = Array.prototype.slice.call(arguments, 1);
    return function(){
        var args = partial_args.concat(Array.prototype.slice.call(arguments));
        return fn.apply(this, args);
    }
}
 
var add = partial(add, 1, 2);
>>> add(3);
6

Hopefully, you can see the call to partial will save the arguments 1 and 2 in partial_args and then the call to add(3), adds 1, 2, and 3 together for a result of 6.

I’m not sure I know where this is particularly useful and I suspect that, since prototype is the only major library that includes a curry function, it isn’t very useful in practice. However a couple places that come to mind are uses in AOP design paradigms like logging and perhaps as a way to apply additional functionality to event handlers.

If you’d like to know more you might want to checkout Functional.js, a library for functional programming in javascript, which includes curry and partial functions.

Copyright © andrew.io/weblog
andrew watts' weblog

Built on Notes Blog Core
Powered by WordPress