Curried Javascript Functions
javascript.crockford.com
javascript.crockford.com
If nothing else, then his lambda() implementation with strings should be enough to convince you to use it.
function curry(fn) {
var wrappedFnMaker = function(accArgs) {
return function() {
var effectiveArgs = accArgs.concat(Array.prototype.slice.call(arguments));
if (effectiveArgs.length >= fn.length) {
return fn.apply(this, effectiveArgs);
} else {
return wrappedFnMaker(effectiveArgs);
}
};
}
return wrappedFnMaker([]);
}
add = curry(function(a,b,c) { return a + b + c; }); function curry(fn, args) {
if (typeof args == "undefined" || args.length < fn.length)
return function() {
if (typeof args == "undefined")
args = [];
return curry(fn, args.concat(Array.prototype.slice.call(arguments)));
};
return fn.apply(this, args);
}
var add = curry(function(a, b, c) { return a + b + c;}); function curry(){
$args = func_get_args();
$fn = array_shift($args);
return function() use(&$fn, &$args) {
$nargs = func_get_args();
foreach($nargs as $narg) $args[] = $narg;
return call_user_func_array($fn, $args);
};
}
$add20 = curry(function($a, $b){return $a + $b;}, 20);
echo $add20(5); #25In principle, these two lines of code should always produce the same result:
foo.bar(1,2)
and foo.bar(1)(2)
And they won't necessarily in our case, if the function uses this.http://prototypejs.org/api/function
String.prototype.splitOnSpaces = String.prototype.split.curry(" "); "foo bar baz thud".splitOnSpaces(); //-> ["foo", "bar", "baz", "thud"]
"foo bar baz thud".splitOnSpaces(); //-> ["foo", "bar", "baz", "thud"]
can be written like this: $w("foo bar baz thud")