Created
December 13, 2013 01:25
-
-
Save NV/7938569 to your computer and use it in GitHub Desktop.
JavaScript named arguments
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
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