Skip to content

Commit

Permalink
Improve S3776: Exclude complexity of JSX short-circuits
Browse files Browse the repository at this point in the history
  • Loading branch information
francoismora committed Nov 30, 2022
1 parent 034ecc7 commit c234a0c
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 2 deletions.
14 changes: 13 additions & 1 deletion src/rules/cognitive-complexity.ts
Expand Up @@ -113,6 +113,9 @@ const rule: TSESLint.RuleModule<string, (number | 'metric' | 'sonar-runtime')[]>
/** Stack of enclosing functions */
const enclosingFunctions: TSESTree.FunctionLike[] = [];

/** Indicator if inside a JSX expression */
let jsx = false;

let secondLevelFunctions: Array<{
node: TSESTree.FunctionLike;
parent: TSESTree.Node | undefined;
Expand Down Expand Up @@ -153,7 +156,12 @@ const rule: TSESLint.RuleModule<string, (number | 'metric' | 'sonar-runtime')[]>
});
}
},

'JSXElement,JSXFragment'() {
jsx = true;
},
'JSXElement,JSXFragment:exit'() {
jsx = false;
},
IfStatement(node: TSESTree.Node) {
visitIfStatement(node as TSESTree.IfStatement);
},
Expand Down Expand Up @@ -339,6 +347,10 @@ const rule: TSESLint.RuleModule<string, (number | 'metric' | 'sonar-runtime')[]>
}

function visitLogicalExpression(logicalExpression: TSESTree.LogicalExpression) {
if (jsx) {
return;
}

if (!consideredLogicalExpressions.has(logicalExpression)) {
const flattenedLogicalExpressions = flattenLogicalExpression(logicalExpression);

Expand Down
46 changes: 45 additions & 1 deletion tests/rules/cognitive-complexity.test.ts
Expand Up @@ -22,7 +22,51 @@ import { ruleTester } from '../rule-tester';
import rule = require('../../src/rules/cognitive-complexity');

ruleTester.run('cognitive-complexity', rule, {
valid: [{ code: `function zero_complexity() {}`, options: [0] }],
valid: [
{ code: `function zero_complexity() {}`, options: [0] },
{
code: `
function Component(obj) {
return (
<span>{ obj.title?.text }</span>
);
}`,
parserOptions: { ecmaFeatures: { jsx: true } },
options: [0],
},
{
code: `
function Component(obj) {
return (
<>
{ obj.isFriendly && <strong>Welcome</strong> }
</>
);
}`,
parserOptions: { ecmaFeatures: { jsx: true } },
options: [0],
},
{
code: `
function Component(obj) {
return (
<span title={ obj.isFriendly || obj.disclaimer }>Text</span>
);
}`,
parserOptions: { ecmaFeatures: { jsx: true } },
options: [0],
},
{
code: `
function Component(obj) {
return (
<button type="button" disabled={ obj.user?.isBot ?? obj.isDemo }>Logout</button>
);
}`,
parserOptions: { ecmaFeatures: { jsx: true } },
options: [0],
},
],
invalid: [
// if
{
Expand Down

0 comments on commit c234a0c

Please sign in to comment.