Skip to content
Permalink
Browse files
Fix: no-constant-condition false positives with unary expressions (#1…
  • Loading branch information
mdjermanovic committed Dec 18, 2020
1 parent 555c128 commit 301d0c05229dbd6cfb1045d716524e8ec46fa2c1
Showing with 22 additions and 3 deletions.
  1. +9 −3 lib/rules/no-constant-condition.js
  2. +13 −0 tests/lib/rules/no-constant-condition.js
@@ -147,12 +147,18 @@ module.exports = {
}

case "UnaryExpression":
if (node.operator === "void") {
if (
node.operator === "void" ||
node.operator === "typeof" && inBooleanPosition
) {
return true;
}

return (node.operator === "typeof" && inBooleanPosition) ||
isConstant(node.argument, true);
if (node.operator === "!") {
return isConstant(node.argument, true);
}

return isConstant(node.argument, false);

case "BinaryExpression":
return isConstant(node.left, false) &&
@@ -32,6 +32,10 @@ ruleTester.run("no-constant-condition", rule, {
"if (`foo${a}` === 'fooa');",
"if (tag`a`);",
"if (tag`${a}`);",
"if (+(a || true));",
"if (-(a || true));",
"if (~(a || 1));",
"if (+(a && 0) === +(b && 0));",
"while(~!a);",
"while(a = b);",
"while(`${a}`);",
@@ -162,6 +166,15 @@ ruleTester.run("no-constant-condition", rule, {
{ code: "if(`foo${0 || 1}`);", errors: [{ messageId: "unexpected", type: "TemplateLiteral" }] },
{ code: "if(`foo${bar}`);", errors: [{ messageId: "unexpected", type: "TemplateLiteral" }] },
{ code: "if(`${bar}foo`);", errors: [{ messageId: "unexpected", type: "TemplateLiteral" }] },
{ code: "if(!(true || a));", errors: [{ messageId: "unexpected", type: "UnaryExpression" }] },
{ code: "if(!(a && void b && c));", errors: [{ messageId: "unexpected", type: "UnaryExpression" }] },
{ code: "if(0 || !(a && null));", errors: [{ messageId: "unexpected", type: "LogicalExpression" }] },
{ code: "if(1 + !(a || true));", errors: [{ messageId: "unexpected", type: "BinaryExpression" }] },
{ code: "if(!(null && a) > 1);", errors: [{ messageId: "unexpected", type: "BinaryExpression" }] },
{ code: "if(+(!(a && 0)));", errors: [{ messageId: "unexpected", type: "UnaryExpression" }] },
{ code: "if(!typeof a === 'string');", errors: [{ messageId: "unexpected", type: "BinaryExpression" }] },
{ code: "if(-('foo' || a));", errors: [{ messageId: "unexpected", type: "UnaryExpression" }] },
{ code: "if(+(void a && b) === ~(1 || c));", errors: [{ messageId: "unexpected", type: "BinaryExpression" }] },


{ code: "while([]);", errors: [{ messageId: "unexpected", type: "ArrayExpression" }] },

0 comments on commit 301d0c0

Please sign in to comment.