Javascript add param when calling a callback function

Advertisements

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?

>Solution :

Functional programming gives us the tools to solve this easily.

// min Length validator
function minLengthValidator(minLength) {
    return function(input) {
        console.log("Length is", input.length, "min Length is", minLength);
        return input.length >= minLength;
    }
}

validate(minLengthValidator(5));

Leave a Reply Cancel reply