Julian Torregrosa
Julian Torregrosa

Reputation: 861

Fix cyclomatic complexity if/else inside loop

If I have a loop with a condition inside like this, where I need an internal and an external variable:

let b = get(b);

for(let a in myArray){
   if(a==b){
     // Do something
   }else{
     // Do another thing
   }
}

How can be the refector in order to reduce cyclomatic complexity. I've tried to extract the condition into another function, but I wonder if there is a best approach.

Upvotes: 0

Views: 327

Answers (1)

James
James

Reputation: 22247

for..in iterates through the property names of an object. If you give it an array, it iterates the indices of the array.

var arr = ['a','b','c'];
for (let i in arr) {
  alert(i); // 0,1,2
  if (i == b) {
    // something
  }
}

So your code checker is spotting the IF condition in this loop and saying HEY, why don't you directly access the property/index you are checking for instead of looping through each property seeing if it's the right one.

var arr = ['a','b','c'];
if (arr[b]) {
  // something
}

Upvotes: 2

Related Questions