1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- var map = require('./map')
- var isArray = require('./isArray')
- function deepGetObj (obj, path) {
- var index = 0
- var len = path.length
- while (obj && index < len) {
- obj = obj[path[index++]]
- }
- return len && obj ? obj : 0
- }
- /**
- * 在list的每个元素上执行方法,任何传递的额外参数都会在调用方法的时候传递给它
- *
- * @param {Array} list
- * @param {Array/String/Function} path
- * @param {...Object} arguments
- * @return {Array}
- */
- function invoke (list, path) {
- var func
- var args = arguments
- var params = []
- var paths = []
- var index = 2
- var len = args.length
- for (; index < len; index++) {
- params.push(args[index])
- }
- if (isArray(path)) {
- len = path.length - 1
- for (index = 0; index < len; index++) {
- paths.push(path[index])
- }
- path = path[len]
- }
- return map(list, function (context) {
- if (paths.length) {
- context = deepGetObj(context, paths)
- }
- func = context[path] || path
- if (func && func.apply) {
- return func.apply(context, params)
- }
- })
- }
- module.exports = invoke
|