How can I reduce cyclomatic complexity for the function

Viewed 112

I have this function which has complexity greater than 12. I am trying to bring down it's complexity. I searched around but couldn't find anything too useful is it possible to reduce this complexity? - if so, how would I go about doing so?

Here is the function

 function sea(name) {    +1
   if (name === 'sa') {         +1
      return 'SA';            +1
    } else if (name === 'uk') {    +1
      return 'UK';             +1
    } else if (name === 'northkorea') {   +1
      return 'NK';                 +1
    } else if (name === 'hongkong') {  +1
      return 'HK';                     +1
    } else {
      var rs = new RegExp(/\w);

      return name.replace(rs, function(up) {        +1
        return up.charAt(0);
      });
    }
  }```
3 Answers

Probably you could use a object to store those country values (like a dictionary), something like this should do the job:

const countries = {
  usa: 'United-States',
  uk: 'United-Kingdom'
  // ... all other countries you want
}

function countryCaps(country) {
  if (countries[country]) {
    return countries[country];
  } else {
    // ... your regex replace function here
  }
}

const country = countryCaps('usa');

console.log(country);

I don't see any need to change this function. It's fine as it is, easily readable and easily testable as well. Just mark it as a false positive in whatever tool this message comes from.

My reasoning would have been entirely different if each of the conditions had a different variable. But since this sequence of if-then-else is like a simple table lookup, it's really the tool that is wrong. It should measure the complexity based on what is really difficult for humans to understand. One such example are deeply nested if statements.

You can do:

// Code refactor
function look(country) {
  const countries = {
    sa: 'South Africa',
    uk: 'United-Kingdom',
    northkorea: 'North-Korea',
    au: 'Australia',
    hongkong: 'Hong-Kong'
  };
  const toUpperCaseFirstLetter = c => c.replace(new RegExp(/\w/), s => s.charAt(0).toUpperCase());

  return countries[country] || toUpperCaseFirstLetter(country);
}

// Testing:
[
  'sa',
  'uk',
  'hongkong',
  'spain', // <-- not in the function's `countries` object
].forEach(c => console.log(look(c)));

Related