Skip to content

Commit

Permalink
Fix: warn constant on RHS of || in no-constant-condition (fixes #11181)…
Browse files Browse the repository at this point in the history
… (#11253)

* Fix: handling of string literals on the right side of logical OR (fixes #11181)

* Fix: handling of string literals on the right side of logical OR (fixes #11181)
  • Loading branch information
Merlin Mason authored and kaicataldo committed Jan 16, 2019
1 parent 9194f45 commit c403445
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/rules/no-constant-condition.js
Expand Up @@ -109,7 +109,10 @@ module.exports = {
const isLeftShortCircuit = (isLeftConstant && isLogicalIdentity(node.left, node.operator));
const isRightShortCircuit = (isRightConstant && isLogicalIdentity(node.right, node.operator));

return (isLeftConstant && isRightConstant) || isLeftShortCircuit || isRightShortCircuit;
return (isLeftConstant && isRightConstant) ||
(node.operator === "||" && isRightConstant && node.right.value) || // in the case of an "OR", we need to know if the right constant value is truthy
isLeftShortCircuit ||
isRightShortCircuit;
}

case "AssignmentExpression":
Expand Down
12 changes: 12 additions & 0 deletions tests/lib/rules/no-constant-condition.js
Expand Up @@ -55,6 +55,12 @@ ruleTester.run("no-constant-condition", rule, {
"if(true && abc==='str' || def ==='str'){}",
"if(true && typeof abc==='string'){}",

// #11181, string literals
"if('str' || a){}",
"if('str1' && a){}",
"if(a && 'str'){}",
"if('str' || abc==='str'){}",

// { checkLoops: false }
{ code: "while(true);", options: [{ checkLoops: false }] },
{ code: "for(;true;);", options: [{ checkLoops: false }] },
Expand Down Expand Up @@ -116,6 +122,12 @@ ruleTester.run("no-constant-condition", rule, {
{ code: "if(false || true){}", errors: [{ messageId: "unexpected", type: "LogicalExpression" }] },
{ code: "if(typeof abc==='str' || true){}", errors: [{ messageId: "unexpected", type: "LogicalExpression" }] },

// #11181, string literals
{ code: "if('str1' || 'str2'){}", errors: [{ messageId: "unexpected", type: "LogicalExpression" }] },
{ code: "if('str1' && 'str2'){}", errors: [{ messageId: "unexpected", type: "LogicalExpression" }] },
{ code: "if(abc==='str' || 'str'){}", errors: [{ messageId: "unexpected", type: "LogicalExpression" }] },
{ code: "if(a || 'str'){}", errors: [{ messageId: "unexpected", type: "LogicalExpression" }] },

{
code: "function* foo(){while(true){} yield 'foo';}",
errors: [{ messageId: "unexpected", type: "Literal" }]
Expand Down

0 comments on commit c403445

Please sign in to comment.