Skip to content

Instantly share code, notes, and snippets.

@koistya
Created March 4, 2012 23:54
Show Gist options
  • Save koistya/1975483 to your computer and use it in GitHub Desktop.
Save koistya/1975483 to your computer and use it in GitHub Desktop.
Partial application of a function
/**
* 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