Skip to content

Instantly share code, notes, and snippets.

@NV
Created December 13, 2013 01:25
Show Gist options
  • Save NV/7938569 to your computer and use it in GitHub Desktop.
Save NV/7938569 to your computer and use it in GitHub Desktop.
JavaScript named arguments
callWithNamed({one: 1, two: 2, three: 3}, function(three, one, two) {
console.log(one, two, three);
});
function callWithNamed(dict, fn, context) {
var newArgs = [];
var parsedArgs = parseArgs(fn);
for (var i = 0; i < parsedArgs.length; i++) {
var name = parsedArgs[i];
if (typeof dict[name] === 'undefined') {
console.warn('Arg %s is missing on', name);
}
newArgs[i] = dict[name];
}
fn.apply(context || null, newArgs);
}
function parseArgs(fn) {
var str = fn.toString();
var startIndex = str.indexOf('(') + 1;
var endIndex = str.indexOf(')', startIndex);
var argsStr = str.slice(startIndex, endIndex);
return argsStr.split(',').map(function(name) {
// TODO: strip comments
return name.trim();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment