[英]How can I reduce cyclomatic complexity for the function
我有这个复杂度大于 12 的 function。我试图降低它的复杂性。 我四处搜索但找不到任何有用的东西是否可以降低这种复杂性? - 如果是这样,我将如何 go 这样做?
这是 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);
});
}
}```
可能您可以使用 object 来存储这些国家/地区值(例如字典),这样的事情应该可以完成:
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);
我认为没有必要更改此 function。 它很好,易于阅读且易于测试。 只需在此消息来自的任何工具中将其标记为误报即可。
如果每个条件都有不同的变量,我的推理就会完全不同。 但是由于这个 if-then-else 序列就像一个简单的查表,所以它确实是错误的工具。 它应该根据人类真正难以理解的内容来衡量复杂性。 一个这样的例子是深度嵌套的 if 语句。
你可以做:
// 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)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.