如何减少函数的圈复杂度

时间:2019-10-17 03:22:28

标签: javascript sonarqube

我具有复杂度大于12的此功能,我试图降低其复杂度。我四处搜寻,但找不到任何有用的方法,是否可以降低这种复杂性? -如果是这样,我该怎么做?

这是功能

 function sea(country) {    +1
   if (country === 'sa') {         +1
      return 'South Africa';            +1
    } else if (country === 'uk') {    +1
      return 'United-Kingdom';             +1
    } else if (country === 'northkorea') {   +1
      return 'North-Korea';                 +1
    } else if (country === 'au') {  +1
      return 'Australia';                   +1
    } else if (country === 'hongkong') {  +1
      return 'Hong-Kong';                     +1
    } else {
      var rs = new RegExp(/\w);

      return country.replace(rs, function(txt) {        +1
        return txt.charAt(0).toUpperCase();
      });
    }
  }```

3 个答案:

答案 0 :(得分:1)

可能您可以使用一个对象来存储这些国家/地区的值(例如字典),类似这样的事情就可以完成:

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);

答案 1 :(得分:0)

我看不到需要更改此功能。很好,很容易阅读,也很容易测试。只要将此消息来自任何工具,就将其标记为误报。

如果每个条件都有不同的变量,我的推理将完全不同。但是,由于此if-then-else序列就像一个简单的表查找一样,因此它实际上是错误的工具。它应该根据人类真正难以理解的内容来衡量复杂性。此类示例深深地嵌套在if语句中。

答案 2 :(得分:0)

您可以这样做:

// 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)));

相关问题