No Description

restArguments.js 1.1KB

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