invoke.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. var map = require('./map')
  2. var isArray = require('./isArray')
  3. function deepGetObj (obj, path) {
  4. var index = 0
  5. var len = path.length
  6. while (obj && index < len) {
  7. obj = obj[path[index++]]
  8. }
  9. return len && obj ? obj : 0
  10. }
  11. /**
  12. * 在list的每个元素上执行方法,任何传递的额外参数都会在调用方法的时候传递给它
  13. *
  14. * @param {Array} list
  15. * @param {Array/String/Function} path
  16. * @param {...Object} arguments
  17. * @return {Array}
  18. */
  19. function invoke (list, path) {
  20. var func
  21. var args = arguments
  22. var params = []
  23. var paths = []
  24. var index = 2
  25. var len = args.length
  26. for (; index < len; index++) {
  27. params.push(args[index])
  28. }
  29. if (isArray(path)) {
  30. len = path.length - 1
  31. for (index = 0; index < len; index++) {
  32. paths.push(path[index])
  33. }
  34. path = path[len]
  35. }
  36. return map(list, function (context) {
  37. if (paths.length) {
  38. context = deepGetObj(context, paths)
  39. }
  40. func = context[path] || path
  41. if (func && func.apply) {
  42. return func.apply(context, params)
  43. }
  44. })
  45. }
  46. module.exports = invoke