transform.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. var arrayEach = require('../internal/arrayEach'),
  2. baseCallback = require('../internal/baseCallback'),
  3. baseCreate = require('../internal/baseCreate'),
  4. baseForOwn = require('../internal/baseForOwn'),
  5. isArray = require('../lang/isArray'),
  6. isFunction = require('../lang/isFunction'),
  7. isObject = require('../lang/isObject'),
  8. isTypedArray = require('../lang/isTypedArray');
  9. /**
  10. * An alternative to `_.reduce`; this method transforms `object` to a new
  11. * `accumulator` object which is the result of running each of its own enumerable
  12. * properties through `iteratee`, with each invocation potentially mutating
  13. * the `accumulator` object. The `iteratee` is bound to `thisArg` and invoked
  14. * with four arguments: (accumulator, value, key, object). Iteratee functions
  15. * may exit iteration early by explicitly returning `false`.
  16. *
  17. * @static
  18. * @memberOf _
  19. * @category Object
  20. * @param {Array|Object} object The object to iterate over.
  21. * @param {Function} [iteratee=_.identity] The function invoked per iteration.
  22. * @param {*} [accumulator] The custom accumulator value.
  23. * @param {*} [thisArg] The `this` binding of `iteratee`.
  24. * @returns {*} Returns the accumulated value.
  25. * @example
  26. *
  27. * _.transform([2, 3, 4], function(result, n) {
  28. * result.push(n *= n);
  29. * return n % 2 == 0;
  30. * });
  31. * // => [4, 9]
  32. *
  33. * _.transform({ 'a': 1, 'b': 2 }, function(result, n, key) {
  34. * result[key] = n * 3;
  35. * });
  36. * // => { 'a': 3, 'b': 6 }
  37. */
  38. function transform(object, iteratee, accumulator, thisArg) {
  39. var isArr = isArray(object) || isTypedArray(object);
  40. iteratee = baseCallback(iteratee, thisArg, 4);
  41. if (accumulator == null) {
  42. if (isArr || isObject(object)) {
  43. var Ctor = object.constructor;
  44. if (isArr) {
  45. accumulator = isArray(object) ? new Ctor : [];
  46. } else {
  47. accumulator = baseCreate(isFunction(Ctor) ? Ctor.prototype : undefined);
  48. }
  49. } else {
  50. accumulator = {};
  51. }
  52. }
  53. (isArr ? arrayEach : baseForOwn)(object, function(value, index, object) {
  54. return iteratee(accumulator, value, index, object);
  55. });
  56. return accumulator;
  57. }
  58. module.exports = transform;