invoke.js 1.5 KB

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