jeudi 3 mai 2018

How to reduce if/else complexity?

I have some if/else statements nested but I want to reduce their overhead. The code:

if (parentIndex === 1) {
  // But its own index is 0
  if (currentIndex === 0) {
    parentIndex = 2;
    updatedIndexPos = array[1];
    mainIndex =list_2.indexOf(updatedIndexPos);
    // If the previous line is -1:
    if (mainIndex === -1) {
      parentIndex = 1;
      updatedIndexPos = filterIndexPos;
      mainIndex = list_1.indexOf(updatedIndexPos);
    }
  } else {
    mainIndex = list_1.indexOf(mainIndexPos);
  }
} else if (parentIndex === 2) {
  // But its own index is 0
  if (currentIndex === 0) {
    parentIndex = 1;
    updatedIndexPos = array[0];
    mainIndex = list_1.indexOf(updatedIndexPos);
    // If the previous line is -1:
    if (mainIndex === -1) {
      parentIndex = 2;
      updatedIndexPos = filterIndexPos;
      mainIndex = list_2.indexOf(updatedIndexPos);
    }
  } else {
    mainIndex = list_2.indexOf(mainIndexPos);
  }
}

Looking at it there's a lot of reused code and eslint is giving me a complexity of 7 for it. I've tried breaking it into smaller functions and passing args but still haven't managed to solve the complexity of this code block.

Aucun commentaire:

Enregistrer un commentaire