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.
recent
- Matador: The Obvious MVC Framework for Node
- Sandboxing JavaScript
- Crouching Ender, hidden command
- Ender.js - The open submodule library
- Qwery - The Tiny Selector Engine
- Klass
- Smallest DOMReady code, ever.
- $script.js - Another JavaScript loader
- About that slowness on Twitter...
- Autocomplete Fuzzy Matching
- JavaScript Cache Provider
- JavaScript Animate
- Asynchronous method queue chaining in JavaScript
- Something changed
- Unofficial Twitter Widget Documentation
i am dustin diaz

