invokeMap.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. var apply = require('./_apply'),
  2. baseEach = require('./_baseEach'),
  3. baseInvoke = require('./_baseInvoke'),
  4. isArrayLike = require('./isArrayLike'),
  5. isKey = require('./_isKey'),
  6. rest = require('./rest');
  7. /**
  8. * Invokes the method at `path` of each element in `collection`, returning
  9. * an array of the results of each invoked method. Any additional arguments
  10. * are provided to each invoked method. If `methodName` is a function, it's
  11. * invoked for and `this` bound to, each element in `collection`.
  12. *
  13. * @static
  14. * @memberOf _
  15. * @since 4.0.0
  16. * @category Collection
  17. * @param {Array|Object} collection The collection to iterate over.
  18. * @param {Array|Function|string} path The path of the method to invoke or
  19. * the function invoked per iteration.
  20. * @param {...*} [args] The arguments to invoke each method with.
  21. * @returns {Array} Returns the array of results.
  22. * @example
  23. *
  24. * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');
  25. * // => [[1, 5, 7], [1, 2, 3]]
  26. *
  27. * _.invokeMap([123, 456], String.prototype.split, '');
  28. * // => [['1', '2', '3'], ['4', '5', '6']]
  29. */
  30. var invokeMap = rest(function(collection, path, args) {
  31. var index = -1,
  32. isFunc = typeof path == 'function',
  33. isProp = isKey(path),
  34. result = isArrayLike(collection) ? Array(collection.length) : [];
  35. baseEach(collection, function(value) {
  36. var func = isFunc ? path : ((isProp && value != null) ? value[path] : undefined);
  37. result[++index] = func ? apply(func, value, args) : baseInvoke(value, path, args);
  38. });
  39. return result;
  40. });
  41. module.exports = invokeMap;