Skip to content

Instantly share code, notes, and snippets.

@koistya
Created March 5, 2012 00:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save koistya/1975645 to your computer and use it in GitHub Desktop.
Save koistya/1975645 to your computer and use it in GitHub Desktop.
Named parameters application of a function
/**
* 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);
}
@koistya
Copy link
Author

koistya commented Mar 5, 2012

Note! It's just a basic implementation, not all the possible scenarios are covered here and performance hasn't been taken into consideration.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment