Home  >  Q&A  >  body text

Inspired by the underscore library, work hard to rewrite the calling function

I'm a beginner trying to rewrite the underline function _.invoke. I'm trying to create the function so that it returns an array containing 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 is with this line:

methodName.call(collection[i]) - Want to call a method on object collection[i], but I want to pass some parameters if they are included in the unit test ).

So far I have tried using the test: typeof(methodName) === "function" and writing a function to test if the method is a function.

P粉990008428P粉990008428173 days ago342

reply all(2)I'll reply

  • P粉165522886

    P粉1655228862024-04-01 09:15:45

    Here you can call with parameters.

    _.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;
    }

    There is a method to test all projects:

    const collection = [...];
    const allHaveMethod = _.invoke(collection, 'method', 'arg1', 'arg2').length === collection.length;

    reply
    0
  • P粉413704245

    P粉4137042452024-04-01 00:23:43

    Is this what you mean?

    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)

    reply
    0
  • Cancelreply