Skip to content

Commit

Permalink
feat: no-constant-binary-expression report unnecessary nullish coales…
Browse files Browse the repository at this point in the history
…cing operator like <expr1> ?? <non-nullish> ?? <expr2>
  • Loading branch information
nissy-dev committed Jan 25, 2023
1 parent d8c8ede commit 99d26bc
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
6 changes: 6 additions & 0 deletions lib/rules/no-constant-binary-expression.js
Expand Up @@ -45,6 +45,12 @@ function hasConstantNullishness(scope, node) {
return (functionName === "Boolean" || functionName === "String" || functionName === "Number") &&
isReferenceToGlobalVariable(scope, node.callee);
}
case "LogicalExpression": {
const isLeftConstant = hasConstantNullishness(scope, node.left);
const isRightConstant = hasConstantNullishness(scope, node.right);

return isLeftConstant || isRightConstant;
}
case "AssignmentExpression":
if (node.operator === "=") {
return hasConstantNullishness(scope, node.right);
Expand Down
8 changes: 7 additions & 1 deletion tests/lib/rules/no-constant-binary-expression.js
Expand Up @@ -308,6 +308,12 @@ ruleTester.run("no-constant-binary-expression", rule, {
{ code: "x === /[a-z]/", errors: [{ messageId: "alwaysNew" }] },

// It's not obvious what this does, but it compares the old value of `x` to the new object.
{ code: "x === (x = {})", errors: [{ messageId: "alwaysNew" }] }
{ code: "x === (x = {})", errors: [{ messageId: "alwaysNew" }] },

{ code: "window.abc && false && anything", errors: [{ messageId: "constantShortCircuit" }] },
{ code: "window.abc || true || anything", errors: [{ messageId: "constantShortCircuit" }] },
{ code: "window.abc ?? 'non-nullish' ?? 'non-nullish'", errors: [{ messageId: "constantShortCircuit" }] },
{ code: "window.abc ?? undefined ?? 'non-nullish'", errors: [{ messageId: "constantShortCircuit" }] },
{ code: "window.abc ?? null ?? 'non-nullish'", errors: [{ messageId: "constantShortCircuit" }] }
]
});

0 comments on commit 99d26bc

Please sign in to comment.