0

I have a concise if/else statement below:

function () {
    if (elem.attr('data-src-1') === '' && elem.attr('data-src-2') === '') {
      // scenario a
    } else if (elem.attr('data-src-1') === '' && elem.attr('data-src-2') !== '') {
      // scenario b
    } else if (elem.attr('data-src-1') !== '' && elem.attr('data-src-2') === '') {
      // scenario c
    } else {
      // scenario d
    }
}

which is returning a complexity of 7 by strict linting rules. I need to reduce its complexity to 6 but can't see how to make it more concise?

Liam
  • 27,717
  • 28
  • 128
  • 190

2 Answers2

2

More readable one (at least for me)

let data1 = elem.attr('data-src-1') === ''
let data2 = elem.attr('data-src-2') === ''

if (data1)
    !data2 ? console.log(" scenario a ")  : console.log(" scenario b ") 
else
    data2 ?  console.log(" scenario c ") : console.log(" scenario d ") 
Margon
  • 511
  • 2
  • 10
  • You could take it one step further and put it all into one giant ternary operation. `data1 ? (!data2 ? console.log(" scenario a ") : console.log(" scenario b ") ) : (data2 ? console.log(" scenario c ") : console.log(" scenario d "))`, but this looks horrible haha – Rich Jun 14 '18 at 15:42
  • But your logic is wrong, `data2` is a/b and `!data2` is c/d, not the way you have it. – Rich Jun 14 '18 at 15:45
1

This is more of a code review question, but you could combine the if 1='' into if/elses, then do the same for the interiors if/elses.

I think this is less readable, but it is technically less complex.

function() {
  if (elem.attr('data-src-1') === '') {
    if (elem.attr('data-src-2') === '') {
      // scenario a
    } 
    else {
      // scenario b
    }
  } else if (elem.attr('data-src-2') === '') {
    // scenario c
  } 
  else {
    // scenario d
  }
}
Rich
  • 1,567
  • 14
  • 24
  • 1
    I re-structured my code to look more like this and it reduced its complexity to 6 - thanks! I will mark this as the answer when I can. – Rebecca O'Riordan Jun 14 '18 at 15:27