A custom eslint rule to check code complexity without optional chaining.
Starting from v9, eslint changed the algorithm of calculating cyclomatic complexity of the code. Now it additionally counts optional chaining. While it matches the complexity formula, these expressions don't actually increase the visual complexity.
For example, the following function has a complexity 4 by the core eslint rule:
function f(a) {
return a?.b?.c?.d;
}
It means the function is equivalent to:
function f(a) {
if (condition) {
if (condition) {
return a;
} else if (condition) {
return b;
} else {
return c;
}
} else {
return d;
}
}
But visually they are quite different.
This plugin extends eslint complexity
rule and
kicks out optional chaining during calculation. It outputs 1 for the first function and 4 for the second one.
There was a request to provide a built-in option to disable optional chaining counting, but it was discarded.
-
Install the package:
npm install -D eslint-plugin-visual-complexity
-
Import and use the plugin in
eslint.config.js
:import visualComplexity from "eslint-plugin-visual-complexity"; export default [ { plugins: { visual: visualComplexity, }, rules: { "visual/complexity": ["error", { max: 6 }], complexity: 0, // <- disable core complexity rule } } // ... ]