SIGN IN SIGN UP

A modern JavaScript utility library delivering modularity, performance, & extras.

0 0 39 JavaScript
2016-10-05 19:29:32 -07:00
define(['./_arrayEach', './_baseCreate', './_baseForOwn', './_baseIteratee', './_getPrototype', './isArray', './isBuffer', './isFunction', './isObject', './isTypedArray'], function(arrayEach, baseCreate, baseForOwn, baseIteratee, getPrototype, isArray, isBuffer, isFunction, isObject, isTypedArray) {
2015-12-16 17:52:15 -08:00
2015-01-08 00:37:01 -08:00
/**
* An alternative to `_.reduce`; this method transforms `object` to a new
2016-04-01 23:28:48 -07:00
* `accumulator` object which is the result of running each of its own
* enumerable string keyed properties thru `iteratee`, with each invocation
2016-05-21 00:48:34 -07:00
* potentially mutating the `accumulator` object. If `accumulator` is not
* provided, a new object with the same `[[Prototype]]` will be used. The
* iteratee is invoked with four arguments: (accumulator, value, key, object).
* Iteratee functions may exit iteration early by explicitly returning `false`.
2015-01-08 00:37:01 -08:00
*
* @static
* @memberOf _
2016-03-26 00:00:01 -07:00
* @since 1.3.0
2015-01-08 00:37:01 -08:00
* @category Object
2016-05-21 00:48:34 -07:00
* @param {Object} object The object to iterate over.
2015-01-08 00:37:01 -08:00
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The custom accumulator value.
* @returns {*} Returns the accumulated value.
* @example
*
2015-12-16 17:46:57 -08:00
* _.transform([2, 3, 4], function(result, n) {
* result.push(n *= n);
* return n % 2 == 0;
2016-01-28 01:16:24 -08:00
* }, []);
2015-12-16 17:46:57 -08:00
* // => [4, 9]
2015-01-08 00:37:01 -08:00
*
2015-12-16 17:53:20 -08:00
* _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
* (result[value] || (result[value] = [])).push(key);
2016-01-28 01:16:24 -08:00
* }, {});
2015-12-16 17:53:20 -08:00
* // => { '1': ['a', 'c'], '2': ['b'] }
2015-01-08 00:37:01 -08:00
*/
2015-12-16 17:53:20 -08:00
function transform(object, iteratee, accumulator) {
2016-10-05 19:29:32 -07:00
var isArr = isArray(object),
isArrLike = isArr || isBuffer(object) || isTypedArray(object);
2015-01-08 00:37:01 -08:00
2016-10-05 19:29:32 -07:00
iteratee = baseIteratee(iteratee, 4);
2015-01-08 00:37:01 -08:00
if (accumulator == null) {
2016-10-05 19:29:32 -07:00
var Ctor = object && object.constructor;
if (isArrLike) {
accumulator = isArr ? new Ctor : [];
}
else if (isObject(object)) {
accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};
}
else {
2015-01-08 00:37:01 -08:00
accumulator = {};
}
}
2016-10-05 19:29:32 -07:00
(isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {
2015-01-08 00:37:01 -08:00
return iteratee(accumulator, value, index, object);
});
return accumulator;
}
return transform;
});