Inspired by the underscore library, work hard to rewrite the calling function
P粉990008428
P粉990008428 2024-03-31 09:42:10
0
2
428

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粉990008428
P粉990008428

reply all(2)
P粉165522886

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;
P粉413704245

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)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template