From c40344566eff2e77a6ae2b2d2dbdbd4ad3e76b67 Mon Sep 17 00:00:00 2001 From: Merlin Mason Date: Wed, 16 Jan 2019 17:53:57 +0000 Subject: [PATCH] Fix: warn constant on RHS of || in no-constant-condition (fixes #11181) (#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) --- lib/rules/no-constant-condition.js | 5 ++++- tests/lib/rules/no-constant-condition.js | 12 ++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/rules/no-constant-condition.js b/lib/rules/no-constant-condition.js index 8d7934d8a59..39c2928eed3 100644 --- a/lib/rules/no-constant-condition.js +++ b/lib/rules/no-constant-condition.js @@ -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": diff --git a/tests/lib/rules/no-constant-condition.js b/tests/lib/rules/no-constant-condition.js index 69a90dd381a..c89f9080d6e 100644 --- a/tests/lib/rules/no-constant-condition.js +++ b/tests/lib/rules/no-constant-condition.js @@ -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 }] }, @@ -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" }]