restArguments.js 1.2 KB

123456789101112131415161718192021222324252627282930313233
  1. define(function () {
  2. // Some functions take a variable number of arguments, or a few expected
  3. // arguments at the beginning and then a variable number of values to operate
  4. // on. This helper accumulates all remaining arguments past the function’s
  5. // argument length (or an explicit `startIndex`), into an array that becomes
  6. // the last argument. Similar to ES6’s "rest parameter".
  7. function restArguments(func, startIndex) {
  8. startIndex = startIndex == null ? func.length - 1 : +startIndex;
  9. return function() {
  10. var length = Math.max(arguments.length - startIndex, 0),
  11. rest = Array(length),
  12. index = 0;
  13. for (; index < length; index++) {
  14. rest[index] = arguments[index + startIndex];
  15. }
  16. switch (startIndex) {
  17. case 0: return func.call(this, rest);
  18. case 1: return func.call(this, arguments[0], rest);
  19. case 2: return func.call(this, arguments[0], arguments[1], rest);
  20. }
  21. var args = Array(startIndex + 1);
  22. for (index = 0; index < startIndex; index++) {
  23. args[index] = arguments[index];
  24. }
  25. args[startIndex] = rest;
  26. return func.apply(this, args);
  27. };
  28. }
  29. return restArguments;
  30. });