Skip to content

Commit

Permalink
Fix: false positive in no-constant-condition (fixes #11306) (#11308)
Browse files Browse the repository at this point in the history
  • Loading branch information
g-plane authored and btmills committed Feb 1, 2019
1 parent 6567c4f commit 5b14ad1
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
20 changes: 19 additions & 1 deletion lib/rules/no-constant-condition.js
Expand Up @@ -5,6 +5,13 @@

"use strict";

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

const EQUALITY_OPERATORS = ["===", "!==", "==", "!="];
const RELATIONAL_OPERATORS = [">", "<", ">=", "<=", "in", "instanceof"];

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
Expand Down Expand Up @@ -110,7 +117,18 @@ module.exports = {
const isRightShortCircuit = (isRightConstant && isLogicalIdentity(node.right, node.operator));

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
(

// in the case of an "OR", we need to know if the right constant value is truthy
node.operator === "||" &&
isRightConstant &&
node.right.value &&
(
!node.parent ||
node.parent.type !== "BinaryExpression" ||
!(EQUALITY_OPERATORS.includes(node.parent.operator) || RELATIONAL_OPERATORS.includes(node.parent.operator))
)
) ||
isLeftShortCircuit ||
isRightShortCircuit;
}
Expand Down
12 changes: 12 additions & 0 deletions tests/lib/rules/no-constant-condition.js
Expand Up @@ -61,6 +61,18 @@ ruleTester.run("no-constant-condition", rule, {
"if(a && 'str'){}",
"if('str' || abc==='str'){}",

// #11306
"if ((foo || 'bar') === 'baz') {}",
"if ((foo || 'bar') !== 'baz') {}",
"if ((foo || 'bar') == 'baz') {}",
"if ((foo || 'bar') != 'baz') {}",
"if ((foo || 233) > 666) {}",
"if ((foo || 233) < 666) {}",
"if ((foo || 233) >= 666) {}",
"if ((foo || 233) <= 666) {}",
"if ((key || 'k') in obj) {}",
"if ((foo || {}) instanceof obj) {}",

// { checkLoops: false }
{ code: "while(true);", options: [{ checkLoops: false }] },
{ code: "for(;true;);", options: [{ checkLoops: false }] },
Expand Down

0 comments on commit 5b14ad1

Please sign in to comment.