-
-
Save FireyFly/1975677 to your computer and use it in GitHub Desktop.
Named parameters 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
/** | |
* 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