Search code examples
javascripttypescriptconditional-statementscoding-stylerefactoring

How I write a clean condition from a "complex" combinations of conditions with && or ||


For example, a have two statement conditions:

First, something similar to

const condition1 = value === '' && value1 === '' && value2 === '' && valu3e === '' && value4 === '' && value5 === ''

and second conditions more simple like

const condition2 = value === 'error'

and my if the statement has the two like this:

if (condition1 || condition2) {
....
}

Has any way to make this better than the actual implementation?


Solution

  • First condition :

    const value = '',
      value1 = '',
      value2 = '',
      value3 = '',
      value4 = '',
      value5 = '';
    
    const condition1 = [
      value,
      value1,
      value2,
      value3,
      value4,
      value5,
    ].every(x => x === '');
    
    console.log(`Condition1 : ${condition1}`);


    If you can refactor the values to be an array it would be better.

    const values = [
      '',
      '',
      '',
      '',
      '',
      '',
    ];
    
    const condition1 = values.every(x => x === '');
    
    console.log(`Condition1 : ${condition1}`);


    Altogether

    const value = '',
      value1 = '',
      value2 = '',
      value3 = '',
      value4 = '',
      value5 = '';
      
    if ([
      value,
      value1,
      value2,
      value3,
      value4,
      value5,
    ].every(x => x === '') || value === 'error') {
      console.log(`Condition : true`);
    } else {
      console.log(`Condition : false`);
    }