I am trying to learn underscorejs source code. The above is a code snippet from underscore.js source code VERSION = '1.9.0'. As you can see the switch block and for loop:
var restArguments = function(func, startIndex) {
startIndex = startIndex == null ? func.length - 1 : +startIndex;
return function() {
var length = Math.max(arguments.length - startIndex, 0),
rest = Array(length),
index = 0;
for (; index < length; index++) {
rest[index] = arguments[index + startIndex];
}
switch (startIndex) {
case 0: return func.call(this, rest);
case 1: return func.call(this, arguments[0], rest);
case 2: return func.call(this, arguments[0], arguments[1], rest);
}
var args = Array(startIndex + 1);
for (index = 0; index < startIndex; index++) {
args[index] = arguments[index];
}
args[startIndex] = rest;
return func.apply(this, args);
};
};
Why did the author handle cases of startIndex [0,1,2] in switch separately.
Is it because the loop will have to be run for these cases and its unnecessary complexity to run such small loops? If that's the reason why did the author select only these 3 cases why not [0,1,2,3].
Is there a reason he picked these 3 only or was it just a choice.