The following code is the source code of negate
function in lodash. As we can see that when the length of parameters less than 4, it uses switch-case
instead of using apply
directly. What magic about this code? Does it make the performance better? And why the split point is 4?
function negate(predicate) {
if (typeof predicate != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return function() {
var args = arguments;
switch (args.length) {
case 0: return !predicate.call(this);
case 1: return !predicate.call(this, args[0]);
case 2: return !predicate.call(this, args[0], args[1]);
case 3: return !predicate.call(this, args[0], args[1], args[2]);
}
return !predicate.apply(this, args);
};
}