Skip to content

noExcessiveCognitiveComplexity

诊断类别:lint/complexity/noExcessiveCognitiveComplexity

¥Diagnostic Category: lint/complexity/noExcessiveCognitiveComplexity

自从:v1.0.0 来源:

¥Since: v1.0.0 Sources:

禁止超过给定认知复杂性分数的函数。

¥Disallow functions that exceed a given Cognitive Complexity score.

函数包含的复杂性越高,以后就越难理解。

¥The more complexity a function contains, the harder it is to understand later on.

降低复杂性有助于使代码更易于维护,既使其更容易理解,又可以减少更改时意外产生副作用的机会。

¥Reducing complexity helps to make code more maintenable, both by making it easier to understand as well as by reducing chances of accidental side-effects when making changes.

此规则为每个函数计算一个复杂性分数,并禁止那些超过配置的复杂性阈值(默认值:15)的函数。

¥This rule calculates a complexity score for every function and disallows those that exceed a configured complexity threshold (default: 15).

复杂度分数基于认知复杂度算法计算:https://redirect.sonarsource.com/doc/cognitive-complexity.html

¥The complexity score is calculated based on the Cognitive Complexity algorithm: https://redirect.sonarsource.com/doc/cognitive-complexity.html

¥Examples

¥Invalid

function tooComplex() {
for (let x = 0; x < 10; x++) {
for (let y = 0; y < 10; y++) {
for (let z = 0; z < 10; z++) {
if (x % 2 === 0) {
if (y % 2 === 0) {
console.log(x > y ? `${x} > ${y}` : `${y} > ${x}`);
}
}
}
}
}
}
code-block.js:1:10 lint/complexity/noExcessiveCognitiveComplexity ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Excessive complexity detected.

> 1 │ function tooComplex() {
^^^^^^^^^^
2 │ for (let x = 0; x < 10; x++) {
3 │ for (let y = 0; y < 10; y++) {

Please refactor this function to reduce its complexity score from 21 to the max allowed complexity 15.

¥Options

允许指定允许的最大复杂度。

¥Allows to specify the maximum allowed complexity.

{
"//": "...",
"options": {
"maxAllowedComplexity": 15
}
}

允许的值范围从 1 到 254。默认值为 15。

¥The allowed values range from 1 through 254. The default is 15.

¥Related links