如何降低函数的圈复杂度

How can I reduce cyclomatic complexity for the function

我有这个复杂度大于 12 的函数。我正在努力降低它的复杂度。我四处搜索但找不到任何有用的东西是否可以降低这种复杂性? - 如果是这样,我该怎么做?

这是函数

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

我认为没有必要更改此功能。它很好,易于阅读,也很容易测试table。只需在这条消息来自的任何工具中将其标记为误报即可。

如果每个条件都有不同的变量,我的推理就会完全不同。但是由于这个 if-then-else 序列就像一个简单的 table 查找,所以它确实是错误的工具。它应该根据人类真正难以理解的东西来衡量复杂性。一个这样的例子是深度嵌套的 if 语句。

也许您可以使用一个对象来存储这些国家/地区值(如字典),像这样的东西应该可以完成这项工作:

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

你可以这样做:

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