Created
March 4, 2012 23:54
-
-
Save koistya/1975483 to your computer and use it in GitHub Desktop.
Partial application of a function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Returns a new function that invokes `func` in a specified context and | |
* with specified set of arguments. | |
* The arguments to this function serve as a template. Undefined values | |
* in the argument list are filled in with values from the inner set. | |
* | |
* Example: var f = function(x, y, z) { return x * (y - z); } | |
* partialApply(f, undefined, 2)(3, 4) // => -6: 3 * (2 - 4) | |
* | |
* @param func {Function} A function to invoke. | |
* @return {Function} A new function with partially applied arguments. | |
*/ | |
function partialApply(func /* , ... */) { | |
var outerArgs = arguments; // Save the outer arguments array | |
return function() { | |
var args = array(outerArgs, 1); // Start with an array of outer args | |
var i = 0, j = 0, len = args.length; | |
// Loop through those args, filling in undefined values from inner | |
for (; i < len; i++) | |
if (args[i] === undefined) args[i] = arguments[j++]; | |
// Now append any remaining inner arguments | |
args = args.concat(array(arguments, j)); | |
return func.apply(this, args); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment