4

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);
1
  • 1
    myMethod(lambda) { return config.some(x => lambda(x) === text); } Commented Nov 7, 2019 at 19:43

2 Answers 2

9

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Hi, I'm getting this error: "x is not defined". Can you please review this line? config.some(x[key] === text)
I don't know where your x is, you used it in your example as if it were defined there.
Ah got it! Then I should do this: config.some(x => x[key] === text). Thanks!
4

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.