Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: false positive in no-constant-condition (fixes #11306) #11308

Merged
merged 1 commit into from
Feb 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 19 additions & 1 deletion lib/rules/no-constant-condition.js
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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