map.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. var arrayMap = require('./_arrayMap'),
  2. baseIteratee = require('./_baseIteratee'),
  3. baseMap = require('./_baseMap'),
  4. isArray = require('./isArray');
  5. /**
  6. * Creates an array of values by running each element in `collection` thru
  7. * `iteratee`. The iteratee is invoked with three arguments:
  8. * (value, index|key, collection).
  9. *
  10. * Many lodash methods are guarded to work as iteratees for methods like
  11. * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
  12. *
  13. * The guarded methods are:
  14. * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
  15. * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
  16. * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
  17. * `template`, `trim`, `trimEnd`, `trimStart`, and `words`
  18. *
  19. * @static
  20. * @memberOf _
  21. * @since 0.1.0
  22. * @category Collection
  23. * @param {Array|Object} collection The collection to iterate over.
  24. * @param {Array|Function|Object|string} [iteratee=_.identity]
  25. * The function invoked per iteration.
  26. * @returns {Array} Returns the new mapped array.
  27. * @example
  28. *
  29. * function square(n) {
  30. * return n * n;
  31. * }
  32. *
  33. * _.map([4, 8], square);
  34. * // => [16, 64]
  35. *
  36. * _.map({ 'a': 4, 'b': 8 }, square);
  37. * // => [16, 64] (iteration order is not guaranteed)
  38. *
  39. * var users = [
  40. * { 'user': 'barney' },
  41. * { 'user': 'fred' }
  42. * ];
  43. *
  44. * // The `_.property` iteratee shorthand.
  45. * _.map(users, 'user');
  46. * // => ['barney', 'fred']
  47. */
  48. function map(collection, iteratee) {
  49. var func = isArray(collection) ? arrayMap : baseMap;
  50. return func(collection, baseIteratee(iteratee, 3));
  51. }
  52. module.exports = map;