i am dustin diaz

a JavaScriptr...

boosh.

don't worry about it.

JavaScript currying

Monday Feb 26 2007

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. Nice to meet you, too. I (actually) build products. Currently founder of an Expa-backed company. Previously @Change, @Medium, @Twitter, @Google, and @Yahoo. I wrote a book called Strobist® Info and was co-author of JavaScript Design Patterns. I co-created the Ender JavaScript Framework, I was an award-winning Photographer, and I pretend to be an amateur Mixologist. Pretend is fun. This is my website. Welcome!

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

Last but not least, recruiters, you are very kind. I’m not looking for work. Cheers.