Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript add param when calling a callback function

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading