1 | import apply from './_apply';
|
2 | import arrayPush from './_arrayPush';
|
3 | import rest from './rest';
|
4 | import toInteger from './toInteger';
|
5 |
|
6 | /** Used as the `TypeError` message for "Functions" methods. */
|
7 | var FUNC_ERROR_TEXT = 'Expected a function';
|
8 |
|
9 | /* Built-in method references for those with the same name as other `lodash` methods. */
|
10 | var nativeMax = Math.max;
|
11 |
|
12 | /**
|
13 | * Creates a function that invokes `func` with the `this` binding of the
|
14 | * create function and an array of arguments much like
|
15 | * [`Function#apply`](http://www.ecma-international.org/ecma-262/6.0/#sec-function.prototype.apply).
|
16 | *
|
17 | * **Note:** This method is based on the
|
18 | * [spread operator](https://mdn.io/spread_operator).
|
19 | *
|
20 | * @static
|
21 | * @memberOf _
|
22 | * @since 3.2.0
|
23 | * @category Function
|
24 | * @param {Function} func The function to spread arguments over.
|
25 | * @param {number} [start=0] The start position of the spread.
|
26 | * @returns {Function} Returns the new function.
|
27 | * @example
|
28 | *
|
29 | * var say = _.spread(function(who, what) {
|
30 | * return who + ' says ' + what;
|
31 | * });
|
32 | *
|
33 | * say(['fred', 'hello']);
|
34 | * // => 'fred says hello'
|
35 | *
|
36 | * var numbers = Promise.all([
|
37 | * Promise.resolve(40),
|
38 | * Promise.resolve(36)
|
39 | * ]);
|
40 | *
|
41 | * numbers.then(_.spread(function(x, y) {
|
42 | * return x + y;
|
43 | * }));
|
44 | * // => a Promise of 76
|
45 | */
|
46 | function spread(func, start) {
|
47 | if (typeof func != 'function') {
|
48 | throw new TypeError(FUNC_ERROR_TEXT);
|
49 | }
|
50 | start = start === undefined ? 0 : nativeMax(toInteger(start), 0);
|
51 | return rest(function(args) {
|
52 | var array = args[start],
|
53 | otherArgs = args.slice(0, start);
|
54 |
|
55 | if (array) {
|
56 | arrayPush(otherArgs, array);
|
57 | }
|
58 | return apply(func, this, otherArgs);
|
59 | });
|
60 | }
|
61 |
|
62 | export default spread;
|