Search code examples
javascriptarraysfunctionlodash

In _.invoke source code, what is the args' role?


I just started to learn JS few months ago and I tried to understand what the "args" doing in "_.invoke" source code. Is there anyone who can answer this, please?

I read mdn .apply and read other _.invoke source codes, but couldn't understand.

  _.invoke = function (collection, functionOrKey, args) {
    if(typeof functionOrKey === "string") {
      return _.map(collection, function(item) {
        return item[functionOrKey].apply(item, args);
      });
    }
    else return _.map(collection, function(item) {
      return functionOrKey.apply(item, args);
    });
  };

test function is like this :

_.invoke(['dog', 'cat'], 'toUpperCase');
      });

      it('runs the specified method on each item in the array, and returns a list of results', function() {
        var upperCasedStrings = _.invoke(['dog', 'cat'], 'toUpperCase');

        expect(upperCasedStrings).to.eql(['DOG', 'CAT']);

in test function, there are no 'args', why!?


Solution

  • All that's happening is you're taking an argument or array of arguments to apply to the function being used to map over the collection - all three are arguments passed to the function.

    It's similar to other methods you might find in libraries like Lodash/Underscore.js - it's essentially a custom mapping function, where you pass the arguments like so:

    let mapped = _.invoke(arr, aFunc, ["anArgument", 2]);
    

    If no arguments are passed, then the function passed doesn't need arguments - toUpperCase doesn't need arguments, so none are needed - therefore none are passed.