|
| 1 | +// Does not include sum or minus, for example, as they don't always evaluate to a boolean |
1 | 2 | const binaryExpressionOperators = ["===", "!==", ">", "<", ">=", "<="]; |
2 | 3 |
|
| 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 | + |
3 | 18 | function checkBooleanValidity(node, context) { |
4 | 19 | const { type } = node; |
5 | 20 |
|
@@ -43,21 +58,14 @@ function checkBooleanValidity(node, context) { |
43 | 58 | checkBooleanValidity(node.alternate, context) |
44 | 59 | ); |
45 | 60 |
|
46 | | - // Example: const a = true; a |
47 | 61 | 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); |
61 | 69 | } |
62 | 70 |
|
63 | 71 | default: |
|
0 commit comments