Skip to content

Commit

Permalink
Fix: no-constant-condition false positives with unary expressions (#1…
Browse files Browse the repository at this point in the history
  • Loading branch information
mdjermanovic committed Dec 18, 2020
1 parent 555c128 commit 301d0c0
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
12 changes: 9 additions & 3 deletions lib/rules/no-constant-condition.js
Expand Up @@ -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) &&
Expand Down
13 changes: 13 additions & 0 deletions tests/lib/rules/no-constant-condition.js
Expand Up @@ -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}`);",
Expand Down Expand Up @@ -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" }] },
Expand Down

0 comments on commit 301d0c0

Please sign in to comment.