I’m a beginner and trying to rewrite an underscore function _.invoke
.
I’m trying to make the function so it returns an array with the results of calling the method on each value in the collection.
_.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
}
I think my problem lays in this line:
methodName.call(collection[i])
– would like to invoke method on an object collection[i]
but I would like to pass some arguments should they be included in the unit test.
I’ve tried so far utilizing the test : typeof(methodName) === "function"
and writing a function that would test whether the method is a function.
2
Answers
Here you can invoke with arguments.
To test that all items have a method:
You mean something like this?