i am dustin diaz

a JavaScriptr...

boosh.

don't worry about it.

JavaScript currying

Currying in JavaScript, in my own opinion, leads to clever programming. It is also one of the places in JavaScript where functional programming wins over object oriented practices. Sometime last year Dan Webb wrote a post on callbacks and partial application which essentially uses a pattern technique called currying. In his article, he gives a few examples which essentially prove the usefulness of currifed JavaScript.

callbacks in JavaScript (paraphrased code from danwebb.net)

// callback function declaration

function update(id) {

    return function(resp) {

        document.getElementById(id).innerHTML = resp.responseText;

    };

}



// currying in action

request('comment.php', update('item'));
Obviously there are implications here that currying is clever. So on that same token, I figured it would have been just as useful to write my very own JavaScript currier function. This was written nearly the same time Dan's article came out, but I'm just now getting to sharing it. It looks like this:

a curry function in JavaScript

function curry (fn, scope) {

    var scope = scope || window;

    var args = [];

    for (var i=2, len = arguments.length; i < len; ++i) {

        args.push(arguments[i]);

    };

    return function() {

	    fn.apply(scope, args);

    };

}

This can be used in many ways. Here are a few:

practical usage of the curry function

/* add a curried function bound to a click event */

var el = document.getElementById('my-element');

el.addEventListener('click', curry(sayHello, el, 'Hello World from Dustin'), false);



function sayHello(msg) {

    alert(msg+'\n You clicked on '+this.id);

}



/* or to use it in the callback example */

request('comment.php', curry(update, window, 'item'));



/* 

or let's say you're subscribing 

to a custom event (eg. YAHOO.util.CustomEvent) 

*/



var myEvent = YAHOO.util.CustomEvent(

    'shake it up', 

    this, 

    true, 

    YAHOO.util.CustomEvent.FLAT

);

myEvent.subscribe(curry(doSomeThingCool, null, 'that', 'requires', 'these', args'));

You can also do a google search for javascript + curry for further information on other implemenations (no, I was not the first one to do this). Cheers.

this is who i am

Hi, my name is Dustin Diaz and I'm an Engineer @ObviousCorp. Previously @Twitter, @Google, and @Yahoo, author of Strobist® Info co-author of JavaScript Design Patterns, co-creator of the Ender JavaScript Framework, a Photographer, and an amateur Mixologist. This is my website. Welcome!

On this site I write about JavaScript. You can also follow along with my open-source work on Github.

This site is optimized and works best in Microsoft Internet Explorer 6.