Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do non short circuit condition in Typescript?

How to evaluate condition in non short circuit way in typescript? Typescript does not allow & or | for boolean type. The reason why I need a non short circuit checking is I call showErrors in function isValueValid.

Given this function

function isValue1Valid(){
  if(value1 === 0) return true;    
  showErrors1();
  return false;
}

function isValue2Valid(){
  if(value2 === 0) return true;    
  showErrors2();
  return false;
}

Then in my condition

if(isValue2Valid() & isValue2Valid()){
//Submit data
}

Although I can do it like this one

if(isValue2Valid() & isValue2Valid()){
//Submit data 
   return;
}
showErrors1()
showErrors2()

But I feel to call it inside isValueValid function. In reality I always think to call show errors by default whenever there's an error.

like image 566
jmvtrinidad Avatar asked Feb 06 '23 02:02

jmvtrinidad


2 Answers

To answer your question, you could do

if ([isValue2Valid(), isValue2Valid()].every(Boolean)) {
    //Submit data
}

to evaluate all function calls and then combine their values. But you really shouldn't have isValueValid call showError in the first place. Instead, make your test functions return the error messages, and then if there are any, show them:

function getValue1Error() {
    if (value1 === 0) return null;
    else return "error1";
}

function getValue2Error() {
    if (value2 === 0) return null; 
    else return "error2";
}

// then:
const errors = [getValue1Error(), getValue2Error()] // or even better, just a loop over your fields
if (errors.some(Boolean)) {
    for (let error of errors)
        showError(error);
} else {
    // Submit data
}
like image 136
Bergi Avatar answered Feb 08 '23 16:02

Bergi


If you want to use functions with side-effects (which is not a good idea in general), it might help to be very explicit about what is called and when:

   var value1Valid = isValue1Valid(); // might show some messages
   var value2Valid = isValue2Valid(); // might show some more messages

   if (value1Valid && value2Valid) {
        // submit data
   }
like image 41
artem Avatar answered Feb 08 '23 15:02

artem