map.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. var arrayMap = require('../internal/arrayMap'),
  2. baseCallback = require('../internal/baseCallback'),
  3. baseMap = require('../internal/baseMap'),
  4. isArray = require('../lang/isArray');
  5. /**
  6. * Creates an array of values by running each element in `collection` through
  7. * `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three
  8. * arguments: (value, index|key, collection).
  9. *
  10. * If a property name is provided for `iteratee` the created `_.property`
  11. * style callback returns the property value of the given element.
  12. *
  13. * If a value is also provided for `thisArg` the created `_.matchesProperty`
  14. * style callback returns `true` for elements that have a matching property
  15. * value, else `false`.
  16. *
  17. * If an object is provided for `iteratee` the created `_.matches` style
  18. * callback returns `true` for elements that have the properties of the given
  19. * object, else `false`.
  20. *
  21. * Many lodash methods are guarded to work as iteratees for methods like
  22. * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
  23. *
  24. * The guarded methods are:
  25. * `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`,
  26. * `drop`, `dropRight`, `every`, `fill`, `flatten`, `invert`, `max`, `min`,
  27. * `parseInt`, `slice`, `sortBy`, `take`, `takeRight`, `template`, `trim`,
  28. * `trimLeft`, `trimRight`, `trunc`, `random`, `range`, `sample`, `some`,
  29. * `sum`, `uniq`, and `words`
  30. *
  31. * @static
  32. * @memberOf _
  33. * @alias collect
  34. * @category Collection
  35. * @param {Array|Object|string} collection The collection to iterate over.
  36. * @param {Function|Object|string} [iteratee=_.identity] The function invoked
  37. * per iteration.
  38. * @param {*} [thisArg] The `this` binding of `iteratee`.
  39. * @returns {Array} Returns the new mapped array.
  40. * @example
  41. *
  42. * function timesThree(n) {
  43. * return n * 3;
  44. * }
  45. *
  46. * _.map([1, 2], timesThree);
  47. * // => [3, 6]
  48. *
  49. * _.map({ 'a': 1, 'b': 2 }, timesThree);
  50. * // => [3, 6] (iteration order is not guaranteed)
  51. *
  52. * var users = [
  53. * { 'user': 'barney' },
  54. * { 'user': 'fred' }
  55. * ];
  56. *
  57. * // using the `_.property` callback shorthand
  58. * _.map(users, 'user');
  59. * // => ['barney', 'fred']
  60. */
  61. function map(collection, iteratee, thisArg) {
  62. var func = isArray(collection) ? arrayMap : baseMap;
  63. iteratee = baseCallback(iteratee, thisArg, 3);
  64. return func(collection, iteratee);
  65. }
  66. module.exports = map;