# complexity

强制执行程序中允许的最大圈复杂度

圈复杂度衡量通过程序源代码的线性独立路径的数量。此规则允许设置圈复杂度阈值。

function a(x) {
    if (true) {
        return x; // 1st path
    } else if (false) {
        return x+1; // 2nd path
    } else {
        return 4; // 3rd path
    }
}

# 规则详情

该规则旨在通过限制程序中允许的圈复杂度来降低代码复杂度。因此,当圈复杂度超过配置的阈值(默认为 20)时,它会发出警告。

最多 2 个错误代码示例:

/*eslint complexity: ["error", 2]*/

function a(x) {
    if (true) {
        return x;
    } else if (false) {
        return x+1;
    } else {
        return 4; // 3rd path
    }
}

function b() {
    foo ||= 1;
    bar &&= 1;
}

最多 2 个的正确代码示例:

/*eslint complexity: ["error", 2]*/

function a(x) {
    if (true) {
        return x;
    } else {
        return 4;
    }
}

function b() {
    foo ||= 1;
}

类字段初始化器和类静态块是隐式函数。因此,它们的复杂度是针对每个初始化器和每个静态块分别计算的,它不会增加封闭代码的复杂度。

最多 2 个的附加错误代码示例:

/*eslint complexity: ["error", 2]*/

class C {
    x = a || b || c; // this initializer has complexity = 3
}

class D { // this static block has complexity = 3
    static {
        if (foo) {
            bar = baz || qux;
        }
    }
}

最多 2 个的附加正确代码示例:

/*eslint complexity: ["error", 2]*/

function foo() { // this function has complexity = 1
    class C {
        x = a + b; // this initializer has complexity = 1
        y = c || d; // this initializer has complexity = 2
        z = e && f; // this initializer has complexity = 2

        static p = g || h; // this initializer has complexity = 2
        static q = i ? j : k; // this initializer has complexity = 2

        static { // this static block has complexity = 2
            if (foo) {
                baz = bar;
            }
        }

        static { // this static block has complexity = 2
            qux = baz || quux;
        }
    }
}

# 选项

或者,您可以指定 max 对象属性:

"complexity": ["error", 2]

相当于

"complexity": ["error", { "max": 2 }]

**已弃用:**对象属性 maximum 已弃用。请改用属性 max

# 何时不使用

如果您无法为您的代码确定适当的复杂性限制,那么最好禁用此规则。

Last Updated: 5/13/2023, 8:55:38 PM