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