Created
February 10, 2015 20:24
-
-
Save letsgetrandy/161e25157d8c979fd26f to your computer and use it in GitHub Desktop.
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
// return an array of argument names | |
function getArgNames(fn) { | |
var matches = fn.toString().match(/\(([a-z_, ]+)\)/i); | |
if (matches.length > 1) { | |
return matches[1].replace(/\s+/g, '').split(','); | |
} | |
return []; | |
} | |
// some sample implementation | |
function somethingCool(callback, context) { | |
var names = getArgNames(callback), | |
args = []; | |
if (!names.length) { | |
// default invokation | |
return callback(); | |
} | |
// deal with named args appropriately | |
for (i=0; i<names.length; i++) { | |
switch(name) { | |
case 'name': | |
args.push('Randy'); | |
break; | |
case 'math': | |
args.push(0.1 + 0.2); | |
break; | |
default: | |
args.push(void 0); | |
break; | |
} | |
} | |
callback.apply(context || this, args); | |
} | |
// invoking the sample with various callbacks | |
somethingCool(function() { | |
console.log('hello world'); | |
}); | |
somethingCool(function(name) { | |
console.log('hello ' + name); | |
}); | |
somethingCool(function(math, name) { | |
console.log('math is hard, ' + name); | |
console.log(math); | |
}); | |
// notice how the order of the argument names doesn't even matter! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment