mirror of
https://github.com/whoisclebs/lodash.git
synced 2026-02-03 00:27:50 +00:00
Bump to v4.0.0.
This commit is contained in:
60
transform.js
Normal file
60
transform.js
Normal file
@@ -0,0 +1,60 @@
|
||||
import arrayEach from './internal/arrayEach';
|
||||
import baseCreate from './internal/baseCreate';
|
||||
import baseForOwn from './internal/baseForOwn';
|
||||
import baseIteratee from './internal/baseIteratee';
|
||||
import isArray from './isArray';
|
||||
import isFunction from './isFunction';
|
||||
import isObject from './isObject';
|
||||
import isTypedArray from './isTypedArray';
|
||||
|
||||
/**
|
||||
* An alternative to `_.reduce`; this method transforms `object` to a new
|
||||
* `accumulator` object which is the result of running each of its own enumerable
|
||||
* properties through `iteratee`, with each invocation potentially mutating
|
||||
* the `accumulator` object. The iteratee is invoked with four arguments:
|
||||
* (accumulator, value, key, object). Iteratee functions may exit iteration
|
||||
* early by explicitly returning `false`.
|
||||
*
|
||||
* @static
|
||||
* @memberOf _
|
||||
* @category Object
|
||||
* @param {Array|Object} object The object to iterate over.
|
||||
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
|
||||
* @param {*} [accumulator] The custom accumulator value.
|
||||
* @returns {*} Returns the accumulated value.
|
||||
* @example
|
||||
*
|
||||
* _.transform([2, 3, 4], function(result, n) {
|
||||
* result.push(n *= n);
|
||||
* return n % 2 == 0;
|
||||
* });
|
||||
* // => [4, 9]
|
||||
*
|
||||
* _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
|
||||
* (result[value] || (result[value] = [])).push(key);
|
||||
* });
|
||||
* // => { '1': ['a', 'c'], '2': ['b'] }
|
||||
*/
|
||||
function transform(object, iteratee, accumulator) {
|
||||
var isArr = isArray(object) || isTypedArray(object);
|
||||
iteratee = baseIteratee(iteratee, 4);
|
||||
|
||||
if (accumulator == null) {
|
||||
if (isArr || isObject(object)) {
|
||||
var Ctor = object.constructor;
|
||||
if (isArr) {
|
||||
accumulator = isArray(object) ? new Ctor : [];
|
||||
} else {
|
||||
accumulator = baseCreate(isFunction(Ctor) ? Ctor.prototype : undefined);
|
||||
}
|
||||
} else {
|
||||
accumulator = {};
|
||||
}
|
||||
}
|
||||
(isArr ? arrayEach : baseForOwn)(object, function(value, index, object) {
|
||||
return iteratee(accumulator, value, index, object);
|
||||
});
|
||||
return accumulator;
|
||||
}
|
||||
|
||||
export default transform;
|
||||
Reference in New Issue
Block a user