Skip to content

Instantly share code, notes, and snippets.

@blankyao
Created August 9, 2011 02:22
Show Gist options
  • Save blankyao/1133286 to your computer and use it in GitHub Desktop.
Save blankyao/1133286 to your computer and use it in GitHub Desktop.
Currying is an expressive and compact alternative to manually wrapping anonymous functions. I use it a lot. But sometimes its not enough – the problem is you can only pre-assign the first n arguments. What if we wanted to make a function and pre-assign th
//from http://javascriptweblog.wordpress.com/2010/05/17/partial-currys-flashy-cousin/
window.___ = {}; //argument placeholder
Function.prototype.partial = function() {
if (arguments.length<1) {
return this; //nothing to pre-assign - return the function as is
}
var __method = this;
var args = arguments;
return function() {
//build up new arg list, for placeholders use current arg, otherwise copy original args
var argIndex = 0, myArgs = [];
for (var i = 0; i < args.length; i++) {
myArgs[i] = window.___==args[i] ? arguments[argIndex++] : args[i];
}
return __method.apply(this, myArgs);
}
}
//eg. Define a remove function:-
String.prototype.remove = String.prototype.replace.partial(___,'');
"12654I 2am2 13not12 3a45 3number3 453".remove(/\d/gi); //"I am not a number"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment