time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

spread.js (1734B)


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