I was recently looking over the promisify-node code to see how the author was able to convert basic functions and objects to a promised-based API. I quickly realized that they were reading function signatures to look for common callback argument names like `callback` and `cb`. The strategy seemed odd but probably necessary.
I took a few minutes to pick out the JavaScript function which parsed argument names for a function and here it is:
function getArgs(func) {
// First match everything inside the function argument parens.
var args = func.toString().match(/functions.*?(([^)]*))/)[1];
// Split the arguments string into an array comma delimited.
return args.split(",").map(function(arg) {
// Ensure no inline comments are parsed and trim the whitespace.
return arg.replace(//*.**//, "").trim();
}).filter(function(arg) {
// Ensure no undefineds are added.
return arg;
});
}
So given the function above and a sample function, here’s how it would work:
function myCustomFn(arg1, arg2,arg3) {
}
console.log(getArgs(myCustomFn)); // ["arg1", "arg2", "arg3"]
Aren’t regular expressions a beautiful thing? I can’t name many uses for such a function but here it is if you’re looking to do such a thing!
Source: David Walsh