jeudi 6 juillet 2017

ES6 function parameter validation

I've read a great pattern of handling required function parameters on 2ality.

function throwIfMissing() {
    throw new Error('Missing parameter');
}
function foo(mustBeProvided = throwIfMissing()) {
    return mustBeProvided;
}

Is there any such nice and clean way to throw validation errors?

function throwIfInvalid(value) {
    const max = 10;
    const min = 5;

    if(value < min || value > max){
        throw new Error(`Value must be between ${min} ${max}`);
    }

    return value;
}

function foo(mustBeValid = throwIfInvalid()) {
    return mustBeValid;
}

Of course the code above does not work. My question is if there is any trick to make it work.?

Aucun commentaire:

Enregistrer un commentaire