as an exercise, I am trying to find the most efficient way to refactor this if...if statement.
This is the original code:
interface Validatable {
value: string | number;
required?: boolean;
minLength?: number;
maxLength?: number;
min?: number;
max?: number;
}
function validate(validatableInput: Validatable) {
let isValid = true;
if (validatableInput.required) {
isValid = isValid && validatableInput.value.toString().trim().length !== 0;
}
if (
validatableInput.minLength != null &&
typeof validatableInput.value === 'string'
) {
isValid =
isValid && validatableInput.value.length >= validatableInput.minLength;
}
if (
validatableInput.maxLength != null &&
typeof validatableInput.value === 'string'
) {
isValid =
isValid && validatableInput.value.length <= validatableInput.maxLength;
}
if (
validatableInput.min != null &&
typeof validatableInput.value === 'number'
) {
isValid = isValid && validatableInput.value >= validatableInput.min;
}
if (
validatableInput.max != null &&
typeof validatableInput.value === 'number'
) {
isValid = isValid && validatableInput.value <= validatableInput.max;
}
return isValid;
}
and this is what I achieved so far:
function validate(validatableInput: Validatable) {
const { required, minLength, maxLength, min, max } = validatableInput; // This methos extracts the properties from the object
const validatableInputValue = validatableInput.value;
let isValid = true;
if (required) {
isValid = isValid && validatableInputValue.toString().trim().length !== 0;
}
if (minLength != null && typeof validatableInputValue === "string") {
isValid = isValid && validatableInputValue.length >= minLength;
}
if (maxLength != null && typeof validatableInputValue === "string") {
isValid = isValid && validatableInputValue.length <= maxLength;
}
if (min != null && typeof validatableInputValue === "number") {
isValid = isValid && validatableInputValue >= min;
}
if (max != null && typeof validatableInputValue === "number") {
isValid = isValid && validatableInputValue <= max;
}
return isValid;
}
Is there anything else I could do? Like use a switch statement instead, or something else? Thank you!
numberandstringso I'd start there. It also doesn't seem like there's any real need to use the previousisValidin any of them--any invalid data means!isValid.