time-to-botec

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

transform.js (2280B)


      1 var arrayEach = require('./_arrayEach'),
      2     baseCreate = require('./_baseCreate'),
      3     baseForOwn = require('./_baseForOwn'),
      4     baseIteratee = require('./_baseIteratee'),
      5     getPrototype = require('./_getPrototype'),
      6     isArray = require('./isArray'),
      7     isBuffer = require('./isBuffer'),
      8     isFunction = require('./isFunction'),
      9     isObject = require('./isObject'),
     10     isTypedArray = require('./isTypedArray');
     11 
     12 /**
     13  * An alternative to `_.reduce`; this method transforms `object` to a new
     14  * `accumulator` object which is the result of running each of its own
     15  * enumerable string keyed properties thru `iteratee`, with each invocation
     16  * potentially mutating the `accumulator` object. If `accumulator` is not
     17  * provided, a new object with the same `[[Prototype]]` will be used. The
     18  * iteratee is invoked with four arguments: (accumulator, value, key, object).
     19  * Iteratee functions may exit iteration early by explicitly returning `false`.
     20  *
     21  * @static
     22  * @memberOf _
     23  * @since 1.3.0
     24  * @category Object
     25  * @param {Object} object The object to iterate over.
     26  * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     27  * @param {*} [accumulator] The custom accumulator value.
     28  * @returns {*} Returns the accumulated value.
     29  * @example
     30  *
     31  * _.transform([2, 3, 4], function(result, n) {
     32  *   result.push(n *= n);
     33  *   return n % 2 == 0;
     34  * }, []);
     35  * // => [4, 9]
     36  *
     37  * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
     38  *   (result[value] || (result[value] = [])).push(key);
     39  * }, {});
     40  * // => { '1': ['a', 'c'], '2': ['b'] }
     41  */
     42 function transform(object, iteratee, accumulator) {
     43   var isArr = isArray(object),
     44       isArrLike = isArr || isBuffer(object) || isTypedArray(object);
     45 
     46   iteratee = baseIteratee(iteratee, 4);
     47   if (accumulator == null) {
     48     var Ctor = object && object.constructor;
     49     if (isArrLike) {
     50       accumulator = isArr ? new Ctor : [];
     51     }
     52     else if (isObject(object)) {
     53       accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};
     54     }
     55     else {
     56       accumulator = {};
     57     }
     58   }
     59   (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {
     60     return iteratee(accumulator, value, index, object);
     61   });
     62   return accumulator;
     63 }
     64 
     65 module.exports = transform;