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);
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);
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With