If you can assume that the toString
of your function hasn't been overridden, you could use it on a user-defined function to check if it has an argument named done
, for example:
function argIndexOf(f, arg) {
var s = f + '';
return s.substring(s.indexOf('(') + 1, s.indexOf(')'))
.replace(/\s+/g, '').split(',').indexOf(arg);
}
argIndexOf(function(){}, 'done'); // -1
argIndexOf(function(done){}, 'done') // 0
argIndexOf(function(arg1, done){}, 'done') // 1
That function would take in a function as an argument and return the position of it's done
argument, or -1
if there is none. It uses Array.prototype.indexOf, which will need to be shimmed if you want to use it in IE 8 or earlier. You've tagged the question node.js
, so I will assume that is not an issue.
You could even add it to Function.prototype, although this is highly discouraged if you want your code to play well with others:
Function.prototype.indexOf = Function.prototype.indexOf || function(arg) {
var s = this + '';
return s.substring(s.indexOf('(') + 1, s.indexOf(')'))
.replace(/\s+/g, '').split(',').indexOf(arg);
};
Then you could just use:
func.indexOf('done')
You can also use apply and it will ignore negative indices, so to call the callback and pass in a value for 'done':
var args = [];
args[func.indexOf('done')] = done_callback;
func.apply(func, args);