Understanding _.invoke
In order to be able to understand how invoke works, I first had to do a bit of research on Javascript’s apply method. Apply is one of the most often used Function methods, as it calls a function with a given this value and a single array (or array-like object) of arguments. Apply is especially useful because you don’t have to know the arguments of the called object, but you can instead just use the arguments object to pass them all in.
The invoke function below calls the method name passed in on each value in the list. We don’t know ahead of time whether the functionOrKey will be a key (a string) or a function name, so need to perform a check on each argument item, first by checking the typeof the input. If it is a string, we then need to assign the value pair to the key as the method before using apply to provide the arguments to the function.
_.invoke = function (collection, functionOrKey, args) {
return _.map(collection, function (item) {
var method;
if (typeof functionOrKey === 'string') {
method = item[functionOrKey];
}
else {
method = functionOrKey;
}
});
return method.apply(item, args);
};
Posted in: hack reactorjavascript