skip to Main Content

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


  1. 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));
    
    Login or Signup to reply.
  2. You can switch the order of parameters for minLengthValidator, then use Function#bind to set the value of the first parameter.

    function minLengthValidator(minLength, input) {
        console.log("Length is", input.length, "min Length is", minLength);
        return input.length >= minLength;
    }
    function validate(callback) {
        let exampleInput = "myText";
        let valid = callback(exampleInput);
        return valid;
    }
    console.log(validate(minLengthValidator.bind(null, 4)));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search