rest.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. var apply = require('./_apply'),
  2. toInteger = require('./toInteger');
  3. /** Used as the `TypeError` message for "Functions" methods. */
  4. var FUNC_ERROR_TEXT = 'Expected a function';
  5. /* Built-in method references for those with the same name as other `lodash` methods. */
  6. var nativeMax = Math.max;
  7. /**
  8. * Creates a function that invokes `func` with the `this` binding of the
  9. * created function and arguments from `start` and beyond provided as
  10. * an array.
  11. *
  12. * **Note:** This method is based on the
  13. * [rest parameter](https://mdn.io/rest_parameters).
  14. *
  15. * @static
  16. * @memberOf _
  17. * @since 4.0.0
  18. * @category Function
  19. * @param {Function} func The function to apply a rest parameter to.
  20. * @param {number} [start=func.length-1] The start position of the rest parameter.
  21. * @returns {Function} Returns the new function.
  22. * @example
  23. *
  24. * var say = _.rest(function(what, names) {
  25. * return what + ' ' + _.initial(names).join(', ') +
  26. * (_.size(names) > 1 ? ', & ' : '') + _.last(names);
  27. * });
  28. *
  29. * say('hello', 'fred', 'barney', 'pebbles');
  30. * // => 'hello fred, barney, & pebbles'
  31. */
  32. function rest(func, start) {
  33. if (typeof func != 'function') {
  34. throw new TypeError(FUNC_ERROR_TEXT);
  35. }
  36. start = nativeMax(start === undefined ? (func.length - 1) : toInteger(start), 0);
  37. return function() {
  38. var args = arguments,
  39. index = -1,
  40. length = nativeMax(args.length - start, 0),
  41. array = Array(length);
  42. while (++index < length) {
  43. array[index] = args[start + index];
  44. }
  45. switch (start) {
  46. case 0: return func.call(this, array);
  47. case 1: return func.call(this, args[0], array);
  48. case 2: return func.call(this, args[0], args[1], array);
  49. }
  50. var otherArgs = Array(start + 1);
  51. index = -1;
  52. while (++index < start) {
  53. otherArgs[index] = args[index];
  54. }
  55. otherArgs[start] = array;
  56. return apply(func, this, otherArgs);
  57. };
  58. }
  59. module.exports = rest;