Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

transform.js 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. var arrayEach = require('./_arrayEach'),
  2. baseCreate = require('./_baseCreate'),
  3. baseForOwn = require('./_baseForOwn'),
  4. baseIteratee = require('./_baseIteratee'),
  5. getPrototype = require('./_getPrototype'),
  6. isArray = require('./isArray'),
  7. isBuffer = require('./isBuffer'),
  8. isFunction = require('./isFunction'),
  9. isObject = require('./isObject'),
  10. isTypedArray = require('./isTypedArray');
  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. module.exports = transform;