Product / version: eslint-plugin-sonarjs 4.2.2, ESLint 10.14.0, Node (flat config)
Rule: sonarjs/cognitive-complexity (S3776)
What happens: when an arrow function is a branch of a conditional expression, every structure after it in the same function gets one extra level of nesting, as if the nesting from the arrow function was never decremented.
Reproducer (threshold set to 0 to show the score):
// Reported complexity: 3 (expected 2)
function withArrow(flag, value) {
const handler = flag ? () => 1 : null;
if (value) {
return handler;
}
return null;
}
// Reported complexity: 2
function withoutArrow(flag, value) {
const handler = flag ? 1 : null;
if (value) {
return handler;
}
return null;
}
// Reported complexity: 2 (same arrow, declared outside the ternary)
function arrowOutside(flag, value) {
const arrow = () => 1;
const handler = flag ? arrow : null;
if (value) {
return handler;
}
return null;
}
Expected: 2 for all three: +1 for the ?: and +1 for the if (nesting 0). In the first function the if is counted as +2, i.e. nested.
// eslint.config.mjs
import sonarjs from "eslint-plugin-sonarjs";
export default [{ files: ["*.js"], plugins: { sonarjs },
rules: { "sonarjs/cognitive-complexity": ["error", 0] } }];
I found this while comparing the rule’s output against my own implementation of the metric on several open source repos.