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

WDubQfBExbixwlBgHxKwymbInHK5gifhZCz2mIbShOXB63ohvqvHPHp6T0uV9MPCub2sHJ52ySu2cWUOkCuNrYpvCqlYuaby6uAiObIeluOTtIXupEgyIe+KBL3vvpeFfWrjMi4DJw57DbWQyVQXfCOFeP0c7731LzNixZHBKNOBWc4jpgBFicymiFCzHzoM7YbKLe4i+1eS14r1BL/L8hbodd+QSzZG4el4JQn1gKF40P19gMB/xkhJUszb0kxA

1j4iLs+J5yW+86kJZyURK0lYiSGjNsu9NBBkAZu6Q9z64CXAS4h7jt+q0EY2NK3r

/*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;
        }
    }
}

1j4iLs+J5yW+86kJZyURK1TqbLPj4NB3W5vuHLw6135/UEAlCBu8GyrxxwKPHycb

/*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;
        }
    }
}

选项

9rc0OLZmbRSJb8m6R1MZOy9INyqmMIkP6DfUGQF3mxP/hYAynYtg95yjRVK7Lq4leRLBejZlVMbzAEAFRzoayw==

"complexity": ["error", 2]

9zP0B2YGAtfzsxBIPQkg0w==

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

hwOoZPeBoMjsckoOCE3Goj8+CQpRvSJqw2qI2SDIXIoH6RYIvUf2lBmDCPF8SaK26g9K6aB70b9PTMPDAOJ4W29FB3Mo1JQS393QiXgN/Y6sLHShDCan6MhW0Epyqc79mcthuZWxqc+SgittuppiKw==

何时不使用

8djWkWUzK4IsZaVxVDJdKiih7yzcLwSKhHN4kCwTU0yyuWfUUvexSKTLeCZITAmgVnmnwfHO8hDlCPMOBpH3W6bhKyH3b3vOStdaCbtjhTwDrfGWzPP+rCOw/alxGh/k