mirror of
https://github.com/whoisclebs/lodash.git
synced 2026-02-04 00:57:48 +00:00
Bump to v3.0.0.
This commit is contained in:
62
object/transform.js
Normal file
62
object/transform.js
Normal file
@@ -0,0 +1,62 @@
|
||||
import arrayEach from '../internal/arrayEach';
|
||||
import baseCallback from '../internal/baseCallback';
|
||||
import baseCreate from '../internal/baseCreate';
|
||||
import baseForOwn from '../internal/baseForOwn';
|
||||
import isArray from '../lang/isArray';
|
||||
import isObject from '../lang/isObject';
|
||||
import isTypedArray from '../lang/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 bound to `thisArg` and invoked
|
||||
* with four arguments; (accumulator, value, key, object). Iterator 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.
|
||||
* @param {*} [thisArg] The `this` binding of `iteratee`.
|
||||
* @returns {*} Returns the accumulated value.
|
||||
* @example
|
||||
*
|
||||
* var squares = _.transform([1, 2, 3, 4, 5, 6], function(result, n) {
|
||||
* n *= n;
|
||||
* if (n % 2) {
|
||||
* return result.push(n) < 3;
|
||||
* }
|
||||
* });
|
||||
* // => [1, 9, 25]
|
||||
*
|
||||
* var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, n, key) {
|
||||
* result[key] = n * 3;
|
||||
* });
|
||||
* // => { 'a': 3, 'b': 6, 'c': 9 }
|
||||
*/
|
||||
function transform(object, iteratee, accumulator, thisArg) {
|
||||
var isArr = isArray(object) || isTypedArray(object);
|
||||
iteratee = baseCallback(iteratee, thisArg, 4);
|
||||
|
||||
if (accumulator == null) {
|
||||
if (isArr || isObject(object)) {
|
||||
var Ctor = object.constructor;
|
||||
if (isArr) {
|
||||
accumulator = isArray(object) ? new Ctor : [];
|
||||
} else {
|
||||
accumulator = baseCreate(typeof Ctor == 'function' && Ctor.prototype);
|
||||
}
|
||||
} 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