Function currying in Javascript

Posted by kerry on Gooder Code See other posts from Gooder Code or by kerry
Published on Wed, 24 Feb 2010 13:55:00 +0000 Indexed on 2010/03/18 23:21 UTC
Read the original article Hit count: 562

Filed under:
|
|

Do you catch yourself doing something like this often?

   1: Ajax.request('/my/url', {'myParam': paramVal}, function() { myCallback(paramVal); });

Creating a function which calls another function asynchronously is a bad idea because the value of paramVal may change before it is called.  Enter the curry function:

   1: Function.prototype.curry = function(scope) {

   2:   var args = [];

   3:   for (var i=1, len = arguments.length; i < len; ++i) {

   4:     args.push(arguments[i]);

   5:   }

   6:   var m = this;

   7:   return function() {

   8:     m.apply(scope, args);

   9:   };

  10: }

This function creates a wrapper around the function and ‘locks in’ the method parameters.  The first parameter is the scope of the function call (usually this or window).  Any remaining parameters will be passed to the method call.  Using the curry method the above call changes to:

   1: Ajax.request('/my/url', {'myParam': paramVal}, myCallback.curry(window,paramVal));

Remember when passing objects to the curry method that the objects members may still change.

© Gooder Code or respective owner

Related posts about Lessons

Related posts about AJAX