Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80742 views
1
var arrayEach = require('../internal/arrayEach'),
2
baseCallback = require('../internal/baseCallback'),
3
baseCreate = require('../internal/baseCreate'),
4
baseForOwn = require('../internal/baseForOwn'),
5
isArray = require('../lang/isArray'),
6
isFunction = require('../lang/isFunction'),
7
isObject = require('../lang/isObject'),
8
isTypedArray = require('../lang/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 bound to `thisArg` and invoked
15
* with four arguments: (accumulator, value, key, object). Iteratee functions
16
* may exit iteration 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
* @param {*} [thisArg] The `this` binding of `iteratee`.
25
* @returns {*} Returns the accumulated value.
26
* @example
27
*
28
* _.transform([2, 3, 4], function(result, n) {
29
* result.push(n *= n);
30
* return n % 2 == 0;
31
* });
32
* // => [4, 9]
33
*
34
* _.transform({ 'a': 1, 'b': 2 }, function(result, n, key) {
35
* result[key] = n * 3;
36
* });
37
* // => { 'a': 3, 'b': 6 }
38
*/
39
function transform(object, iteratee, accumulator, thisArg) {
40
var isArr = isArray(object) || isTypedArray(object);
41
iteratee = baseCallback(iteratee, thisArg, 4);
42
43
if (accumulator == null) {
44
if (isArr || isObject(object)) {
45
var Ctor = object.constructor;
46
if (isArr) {
47
accumulator = isArray(object) ? new Ctor : [];
48
} else {
49
accumulator = baseCreate(isFunction(Ctor) ? Ctor.prototype : null);
50
}
51
} else {
52
accumulator = {};
53
}
54
}
55
(isArr ? arrayEach : baseForOwn)(object, function(value, index, object) {
56
return iteratee(accumulator, value, index, object);
57
});
58
return accumulator;
59
}
60
61
module.exports = transform;
62
63