_.invoke
。
我正在尝试创建该函数,以便它返回一个数组,其中包含对集合中的每个值调用该方法的结果。
_.invoke = function(collection, methodName) {
var result = [];
if (Array.isArray(collection)) {
for (let i = 0; i < collection.length; i++) {
methodName.call(collection[i])
var value = collection[i][methodName]
result.push(value)
}
}
return result
}
我认为我的问题出在这一行:
methodName.call(collection[i])
- 想在对象上调用方法collection[i]
,但我想传递一些参数(如果它们包含在单元测试中)。
到目前为止,我已经尝试使用测试:
typeof(methodName) === "function"
并编写一个函数来测试该方法是否是一个函数。
你的意思是这样的吗?
const myArr = [
{ cons:function(args) { return args } },
{ cons:function(args) { return args["bla"] } },
]
const _ = {};
_.invoke = (collection, methodName, ...args) => !Array.isArray(collection) ? [] : collection
.filter(item => typeof item[methodName] === 'function')
.map(item => item[methodName].apply(item, args));
const res = _.invoke(myArr,"cons",{"bla":"hello"})
console.log(res)
如果您需要处理大量条目的速度,这是一个性能更高的版本
const myArr = [
{ cons: function(args) { return args; } },
{ cons: function(args) { return args["bla"]; } },
];
const _ = {};
_.invoke = (collection, methodName, ...args) => {
const result = [];
if (!Array.isArray(collection)) return result;
for (let i = 0, len = collection.length; i < len; i++) {
const item = collection[i];
const method = item[methodName];
if (typeof method === 'function') {
result.push(method.apply(item, args));
}
}
return result;
};
const res = _.invoke(myArr, "cons", {
"bla": "hello"
});
console.log(res);
在这里您可以使用参数进行调用。
_.invoke = function(collection, methodName, ...args) {
if (!Array.isArray(collection)) {
return [];
}
const out = [];
for(const item of collection){
if(typeof item[methodName] === 'function')
out.push(item[methodName].apply(item, args));
}
}
return out;
}
要测试所有项目都有一个方法:
const collection = [...];
const allHaveMethod = _.invoke(collection, 'method', 'arg1', 'arg2').length === collection.length;