Skip to content

Instantly share code, notes, and snippets.

@FireyFly
Forked from koistya/gist:1975645
Created March 5, 2012 00:42
Show Gist options
  • Save FireyFly/1975677 to your computer and use it in GitHub Desktop.
Save FireyFly/1975677 to your computer and use it in GitHub Desktop.
Named parameters application of a function
/**
* Applies a set of named arguments to a `func`.
*
* Example: var f = function(x, y, z) { return x * (y - z); };
* namedApply(f, {x: 1, y: 2, z: 3});
*
* @param func {Function} A function to invoke.
* @param args {Object} A collection of named arguments.
* @return {Function} A new function with partially applied named arguments.
*/
function namedApply(func, args) {
var len = Object.getOwnPropertyNames(args).length;
func.apply(this, func.toString().match(/\((.*?)\)/)[1].split(", ").map(function(name, i) {
if (i > len) throw TypeError("`args` object has more properties than parameters in a function.");
return args[name];
}));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment