UNPKG

2.28 kBJavaScriptView Raw
1import arrayEach from './_arrayEach.js';
2import baseCreate from './_baseCreate.js';
3import baseForOwn from './_baseForOwn.js';
4import baseIteratee from './_baseIteratee.js';
5import getPrototype from './_getPrototype.js';
6import isArray from './isArray.js';
7import isBuffer from './isBuffer.js';
8import isFunction from './isFunction.js';
9import isObject from './isObject.js';
10import isTypedArray from './isTypedArray.js';
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 */
42function 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
65export default transform;