I want to set additional Parameters to callback function when defining it.
// min Length validator
function minLengthValidator(input, minLength) {
console.log("Length is", input.length, "min Length is", minLength);
return input.length >= minLength;
}
// using the callback in an validate function (e.g. on an Input field) and only give it the input value
function validate(callback) {
let exampleInput = "myText";
let valid = callback(exampleInput);
return valid;
}
// call the validate function
validate(minLengthValidator);
But how do I set the minLength property on the minLengthValidator
function? The value gets passed in by the validate function but how to pass the minLength?
You can always define a custom function for each and call the minLengthValidator function in it:
validate((value) => { return minLengthValidator(value, 4);});
but is there a better way?
2
Answers
Functional programming gives us the tools to solve this easily.
You can switch the order of parameters for
minLengthValidator
, then useFunction#bind
to set the value of the first parameter.