Search code examples
javascriptalgorithmif-statementgenericsconditional-statements

How to refactor nested if condition in a function to reduce cognitive complexity in sonar?


In my component, i have written one function for conditional check to disable/enable a button. There are multiple nested conditional check. While running, i am getting 'Reduce coginitive complexity' error in sonar and it is critical.

Here is my function

    const isButtonSubmit = computed(() => {
  let disableButton = false;
  if (formInput.value.radio3 === 'yes') {
    if (formInput.value.input1 === '') {
      disableButton = true;
    }
  }
  if (formInput.value.radio4 === 'yes') {
    if (formInput.value.input2 === '') {
      disableButton = true;
    }
  }
  if (formInput.value.radio4 === 'no') {
    if (formInput.value.input6 === '') {
      disableButton = true;
    }
  }
  if (formInput.value.radio5 === 'no') {
    if (formInput.value.input3 === '') {
      disableButton = true;
    }
  }
  if (formInput.value.radio6 === 'yes') {
    if (formInput.value.input4 === '') {
      disableButton = true;
    }
  }
  if (formInput.value.radio6 === 'no') {
    if (formInput.value.input5 === '') {
      disableButton = true;
    }
  }
  if (formInput.value.radio7 === 'no') {
    if (formInput.value.input7 === '') {
      disableButton = true;
    }
  }
  if (formInput.value.radio8 === 'no') {
    if (formInput.value.input8 === '') {
      disableButton = true;
    }
  }
  if (formInput.value.radio9 === 'no') {
    if (formInput.value.input9 === '') {
      disableButton = true;
    }
  }
  return disableButton;
});

I am getting the warning related to cognitive complexity because of these conditional checks. Please let me know how to resolve this?


Solution

  • The approach to issues like this is always the same, you have to extract the data from the structure and then find a way to apply it efficiently. You should end up with more maintainable and compact code.

    In your case, this could be something like this:

    const disableStates = [
      {radio: 'radio3', value: 'yes', input: 'input1'},
      {radio: 'radio4', value: 'yes', input: 'input2'},
      ...
    ]
    const isButtonSubmit = computed(() => {
      const i = formInput.value
      return disableStates.some(({radio, value, input}) => i[radio] === value && i[input] === '')
    }