mirror of https://github.com/lukechilds/node.git
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
60 lines
1.6 KiB
60 lines
1.6 KiB
9 years ago
|
var apply = require('./_apply'),
|
||
|
arrayPush = require('./_arrayPush'),
|
||
|
rest = require('./rest'),
|
||
|
toInteger = require('./toInteger');
|
||
|
|
||
10 years ago
|
/** Used as the `TypeError` message for "Functions" methods. */
|
||
|
var FUNC_ERROR_TEXT = 'Expected a function';
|
||
|
|
||
9 years ago
|
/* Built-in method references for those with the same name as other `lodash` methods. */
|
||
|
var nativeMax = Math.max;
|
||
|
|
||
10 years ago
|
/**
|
||
|
* Creates a function that invokes `func` with the `this` binding of the created
|
||
|
* function and an array of arguments much like [`Function#apply`](https://es5.github.io/#x15.3.4.3).
|
||
|
*
|
||
9 years ago
|
* **Note:** This method is based on the [spread operator](https://mdn.io/spread_operator).
|
||
10 years ago
|
*
|
||
|
* @static
|
||
|
* @memberOf _
|
||
|
* @category Function
|
||
|
* @param {Function} func The function to spread arguments over.
|
||
9 years ago
|
* @param {number} [start=0] The start position of the spread.
|
||
10 years ago
|
* @returns {Function} Returns the new function.
|
||
|
* @example
|
||
|
*
|
||
|
* var say = _.spread(function(who, what) {
|
||
|
* return who + ' says ' + what;
|
||
|
* });
|
||
|
*
|
||
|
* say(['fred', 'hello']);
|
||
|
* // => 'fred says hello'
|
||
|
*
|
||
|
* var numbers = Promise.all([
|
||
|
* Promise.resolve(40),
|
||
|
* Promise.resolve(36)
|
||
|
* ]);
|
||
|
*
|
||
|
* numbers.then(_.spread(function(x, y) {
|
||
|
* return x + y;
|
||
|
* }));
|
||
|
* // => a Promise of 76
|
||
|
*/
|
||
9 years ago
|
function spread(func, start) {
|
||
10 years ago
|
if (typeof func != 'function') {
|
||
|
throw new TypeError(FUNC_ERROR_TEXT);
|
||
|
}
|
||
9 years ago
|
start = start === undefined ? 0 : nativeMax(toInteger(start), 0);
|
||
|
return rest(function(args) {
|
||
|
var array = args[start],
|
||
|
otherArgs = args.slice(0, start);
|
||
|
|
||
|
if (array) {
|
||
|
arrayPush(otherArgs, array);
|
||
|
}
|
||
|
return apply(func, this, otherArgs);
|
||
|
});
|
||
10 years ago
|
}
|
||
|
|
||
|
module.exports = spread;
|