Skip to content

Commit 360b7de

Browse files
committed
refactor: improve the readability of the identifier function
1 parent 9788fe0 commit 360b7de

File tree

2 files changed

+27
-14
lines changed

2 files changed

+27
-14
lines changed

src/rules/jsx-explicit-boolean.test.tsx

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,5 +149,10 @@ ruleTester.run("jsx-explicit-boolean", require("./jsx-explicit-boolean"), {
149149
errors: [{ messageId: "booleanConversion" }],
150150
output: "const a = undefined; Boolean(a) && <div />;",
151151
},
152+
{
153+
code: "const a = 0 + 0; a && <div />;",
154+
errors: [{ messageId: "booleanConversion" }],
155+
output: "const a = 0 + 0; Boolean(a) && <div />;",
156+
},
152157
],
153158
});

src/rules/jsx-explicit-boolean.ts

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,20 @@
1+
// Does not include sum or minus, for example, as they don't always evaluate to a boolean
12
const binaryExpressionOperators = ["===", "!==", ">", "<", ">=", "<="];
23

4+
function findVariable(context, nodeName) {
5+
let scope = context.getScope();
6+
7+
// Traverse the scope chain until we find the variable
8+
while (scope) {
9+
const variable = scope.variables.find((v) => v.name === nodeName);
10+
if (variable) return variable;
11+
12+
scope = scope.upper;
13+
}
14+
15+
return null;
16+
}
17+
318
function checkBooleanValidity(node, context) {
419
const { type } = node;
520

@@ -43,21 +58,14 @@ function checkBooleanValidity(node, context) {
4358
checkBooleanValidity(node.alternate, context)
4459
);
4560

46-
// Example: const a = true; a
4761
case "Identifier": {
48-
let scope = context.getScope();
49-
while (scope) {
50-
const variable = scope.variables.find((v) => v.name === node.name);
51-
if (variable) {
52-
return variable.defs.some(
53-
(def) =>
54-
def.type === "Variable" &&
55-
checkBooleanValidity(def.node.init, context)
56-
);
57-
}
58-
scope = scope.upper;
59-
}
60-
return false;
62+
const variable = findVariable(context, node.name);
63+
if (!variable) return false;
64+
65+
const variableDef = variable.defs.find((def) => def.type === "Variable");
66+
if (!variableDef) return false;
67+
68+
return checkBooleanValidity(variableDef.node.init, context);
6169
}
6270

6371
default:

0 commit comments

Comments
 (0)