0

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.

  • Cyclomatic complexity isn't so much "fixed" as it is "reduced", and there's always a minimum amount of complexity. I don't see how this can be improved, but you might try asking on [codereview.se] –  Oct 24 '18 at 19:48

1 Answers1

2

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
}
James
  • 20,957
  • 5
  • 26
  • 41
  • Nice solution, what if it is an array of objects? for example with for...of – Julian Torregrosa Oct 24 '18 at 21:59
  • 1
    If you are searching for a value in an array you can use array.indexOf to locate simple elements and array.find/array.findIndex for more complex data. – James Oct 25 '18 at 02:21