Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass lambda as parameter in Javascript?

I have a big function in Javascript that I need to repeat the same logic, except for the line bellow, that is different:

config.some(x => x.site === text)

The other function will do the same thing, but instead of filtering by SITE, it will filter by NAME:

config.some(x => x.name === text)

I want to pass SITE or NAME as a parameter to the method. How can I do this?

I was hoping for something like this:

myMethod(lambda) {
   config.some(lambda === text)
}

And call like:

this.myMethod(x => x.site);
like image 947
alansiqueira27 Avatar asked Oct 29 '25 01:10

alansiqueira27


2 Answers

If you want to pass the parameter name it could be done like this:

myMethod(key) {
   config.some(x => x[key] === text)
}
myMethod('name');

A "lambda" passing implementation would look like:

myMethod(lambda) {
   config.some(x => lambda(x) === text)
}
const nameLambda = (x) => x.name;
myMethod(nameLambda);
like image 103
Vlad Vidac Avatar answered Oct 31 '25 16:10

Vlad Vidac


You can pass the lambda argument directly to the some function.
Here is an example with filter.

function methodWithLambda(lambda) {
  let data = [
    1,2,3,4,5,6,7,8
  ]
  
  return data.filter(lambda);
}

console.log(methodWithLambda(x => x > 4));
console.log(methodWithLambda(x => x < 7));
like image 26
Nicolas Avatar answered Oct 31 '25 17:10

Nicolas