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?
2
Answers
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:
The OP could utilize an object literal as configuration which does map all the related data which define the computed button value as disabled. The next provided example code does so by iterating the array of all involved element keys, where for each key one retrieves its related form input value and from the latter the effected configuration for comparing values. The provided data structure is as generic as possible from the element-value side thus still open to changes which target element values individually …