spread.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /** Used as the `TypeError` message for "Functions" methods. */
  2. var FUNC_ERROR_TEXT = 'Expected a function';
  3. /**
  4. * Creates a function that invokes `func` with the `this` binding of the created
  5. * function and an array of arguments much like [`Function#apply`](https://es5.github.io/#x15.3.4.3).
  6. *
  7. * **Note:** This method is based on the [spread operator](https://developer.mozilla.org/Web/JavaScript/Reference/Operators/Spread_operator).
  8. *
  9. * @static
  10. * @memberOf _
  11. * @category Function
  12. * @param {Function} func The function to spread arguments over.
  13. * @returns {Function} Returns the new function.
  14. * @example
  15. *
  16. * var say = _.spread(function(who, what) {
  17. * return who + ' says ' + what;
  18. * });
  19. *
  20. * say(['fred', 'hello']);
  21. * // => 'fred says hello'
  22. *
  23. * // with a Promise
  24. * var numbers = Promise.all([
  25. * Promise.resolve(40),
  26. * Promise.resolve(36)
  27. * ]);
  28. *
  29. * numbers.then(_.spread(function(x, y) {
  30. * return x + y;
  31. * }));
  32. * // => a Promise of 76
  33. */
  34. function spread(func) {
  35. if (typeof func != 'function') {
  36. throw new TypeError(FUNC_ERROR_TEXT);
  37. }
  38. return function(array) {
  39. return func.apply(this, array);
  40. };
  41. }
  42. module.exports = spread;