transform.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import arrayEach from './_arrayEach.js';
  2. import baseCreate from './_baseCreate.js';
  3. import baseForOwn from './_baseForOwn.js';
  4. import baseIteratee from './_baseIteratee.js';
  5. import getPrototype from './_getPrototype.js';
  6. import isArray from './isArray.js';
  7. import isBuffer from './isBuffer.js';
  8. import isFunction from './isFunction.js';
  9. import isObject from './isObject.js';
  10. import isTypedArray from './isTypedArray.js';
  11. /**
  12. * An alternative to `_.reduce`; this method transforms `object` to a new
  13. * `accumulator` object which is the result of running each of its own
  14. * enumerable string keyed properties thru `iteratee`, with each invocation
  15. * potentially mutating the `accumulator` object. If `accumulator` is not
  16. * provided, a new object with the same `[[Prototype]]` will be used. The
  17. * iteratee is invoked with four arguments: (accumulator, value, key, object).
  18. * Iteratee functions may exit iteration early by explicitly returning `false`.
  19. *
  20. * @static
  21. * @memberOf _
  22. * @since 1.3.0
  23. * @category Object
  24. * @param {Object} object The object to iterate over.
  25. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  26. * @param {*} [accumulator] The custom accumulator value.
  27. * @returns {*} Returns the accumulated value.
  28. * @example
  29. *
  30. * _.transform([2, 3, 4], function(result, n) {
  31. * result.push(n *= n);
  32. * return n % 2 == 0;
  33. * }, []);
  34. * // => [4, 9]
  35. *
  36. * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
  37. * (result[value] || (result[value] = [])).push(key);
  38. * }, {});
  39. * // => { '1': ['a', 'c'], '2': ['b'] }
  40. */
  41. function transform(object, iteratee, accumulator) {
  42. var isArr = isArray(object),
  43. isArrLike = isArr || isBuffer(object) || isTypedArray(object);
  44. iteratee = baseIteratee(iteratee, 4);
  45. if (accumulator == null) {
  46. var Ctor = object && object.constructor;
  47. if (isArrLike) {
  48. accumulator = isArr ? new Ctor : [];
  49. }
  50. else if (isObject(object)) {
  51. accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};
  52. }
  53. else {
  54. accumulator = {};
  55. }
  56. }
  57. (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {
  58. return iteratee(accumulator, value, index, object);
  59. });
  60. return accumulator;
  61. }
  62. export default transform;