The following code is taken from the reference here:
function isBigEnough(value) {
return value >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]
I want to know if I can dynamically change the value of 10
in the return
line by passing in a variable. From the reference I cannot figure out how to do this. I want to call the same filter callback but pass in a unique value for a regex test.
So it would look something like:
function isBigEnough(value, num) {
return value >= num;
}
The easiest way would be simply to use an anonymous function and close over the variable you want to use:
var minSize = 10;
var filtered = [12, 5, 8, 130, 44].filter( val => val >= minSize );
If you really wanted to keep a named function to call back to, you could partially apply a parameter with bind:
function isBigEnough(minSize, value) {
return value >= minSize;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough.bind(null,10));
Here, bind will return a new function with the leftmost parameter bound to 10 (the first argument, the one that is null, is what gets passed as this
to the function when being invoked). So the parameter that filter passes in will show up as the second value in the callback.
Try this
function isBigEnough(num) {
return function(value) {
return value >= num;
}
}
And then
[12, 5, 8, 130, 44].filter(isBigEnough(10));
How does this work?
isBigEnough(10)
returns an anonymous functionIf 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