invoke.js 875 B

123456789101112131415161718192021222324252627282930
  1. var restArguments = require('./restArguments.js');
  2. var isFunction = require('./isFunction.js');
  3. var map = require('./map.js');
  4. var _deepGet = require('./_deepGet.js');
  5. var _toPath = require('./_toPath.js');
  6. // Invoke a method (with arguments) on every item in a collection.
  7. var invoke = restArguments(function(obj, path, args) {
  8. var contextPath, func;
  9. if (isFunction(path)) {
  10. func = path;
  11. } else {
  12. path = _toPath(path);
  13. contextPath = path.slice(0, -1);
  14. path = path[path.length - 1];
  15. }
  16. return map(obj, function(context) {
  17. var method = func;
  18. if (!method) {
  19. if (contextPath && contextPath.length) {
  20. context = _deepGet(context, contextPath);
  21. }
  22. if (context == null) return void 0;
  23. method = context[path];
  24. }
  25. return method == null ? method : method.apply(context, args);
  26. });
  27. });
  28. module.exports = invoke;