Created
March 5, 2012 00:33
-
-
Save koistya/1975645 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 `fn`. | |
* | |
* Example: var f = function(x, y, z) { return x * (y - z); }; | |
* namedApply(f, {x: 1, y: 2, z: 3}); | |
* | |
* @param fn {Function} A function to invoke. | |
* @param args {Object} A collection of named arguments. | |
*/ | |
function namedApply(fn, args) { | |
// Validation | |
if (typeof(fn) != "function") | |
throw new TypeError("namedApply(fn, args): `fn` must be a function"); | |
// Make sure `args` is not null or undefined | |
args = args || {}; | |
// Converts `args` object into array with arguments to be passed into `fn` | |
args = fn.toString() | |
// Gets a list of parameter names from `fn` body | |
// TODO: make it work with embeded comments: function (a, b /* optional */) { } | |
// and also optimization is needed | |
.match(/function[^(]*\((.*?)\)/)[1].split(/\s*,\s*/) | |
// Maps parameter names to values from `args` | |
.map(function(name){ return args[name] }); | |
return fn.apply(this, args); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note! It's just a basic implementation, not all the possible scenarios are covered here and performance hasn't been taken into consideration.