spread.js (1068B)
1 /** Used as the `TypeError` message for "Functions" methods. */ 2 var FUNC_ERROR_TEXT = 'Expected a function'; 3 4 /** 5 * Creates a function that invokes `func` with the `this` binding of the 6 * created function and the array of arguments provided to the created 7 * function much like [Function#apply](http://es5.github.io/#x15.3.4.3). 8 * 9 * @static 10 * @memberOf _ 11 * @category Function 12 * @param {Function} func The function to spread arguments over. 13 * @returns {*} Returns the new function. 14 * @example 15 * 16 * var spread = _.spread(function(who, what) { 17 * return who + ' says ' + what; 18 * }); 19 * 20 * spread(['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 43 module.exports = spread;