3 ms·
In `maybe`, would it make sense to check the args passed to the wrapper against the number of args the original function expects? Something like this: func
by wylee 14y ago
In `maybe`, would it make sense to check the args passed to the wrapper against the number of args the original function expects? Something like this:
function maybe (fn) {
var expected_number_of_args = fn.length;
return function () {
var i, arg;
for (i = 0; i < expected_number_of_args; ++i) {
arg = arguments[i];
if (arg === null || typeof arg === 'undefined') {
return null;
}
}
return fn.apply(this, arguments)
}
}
- jrajav 14y agoThis would make it unusable for a function that, itself, uses the 'arguments' variable rather than formal arguments. Function arity in Javascript is a tricky subject when we touch on partial application and other functional programming techniques that act on the arguments passed to a function, but the generally accepted solution is to avoid Function#length and ignore that formal arguments exist.
- wylee 14y agoThe `maybe` in the article allows for this ambiguous situation: var fn = function (a, b) { ... }; var maybe_fn = maybe(fn); var obj = {}; maybe_fn(1); // calls fn maybe_fn(1, null); // doesn't call fn maybe_fn(1, obj.nonexistent_prop); // also doesn't call fn In my mind, all of these calls to `maybe_fn` should do the same thing. Maybe not, though?
- jrajav 14y agoThis is a good point, and may be an argument for having a "formal_maybe" or perhaps having it check at least as many arguments as there are formal arguments. However, I don't think that this situation would be as important in practical use. You would normally use this function to allow for passed arguments to be null or undefined - not to allow for some arguments not to be passed.
- ufo 14y agofunction.length is certainy a PITA dus to the `arguments` issue that was mentioned. In particular, function.length doesn't work on functions returned by our own combinators, a big no-no! In the end I adopted a convention where every function that depends on the number of arguments of something else receives that number sa a first parameter: maybe(2, function(a,b){ ... })