Skip to content

Commit

Permalink
feat: Treat Class/New Expressions as truthy in no-constant-condition
Browse files Browse the repository at this point in the history
  • Loading branch information
captbaritone committed Nov 24, 2021
1 parent 388eb7e commit 286cf80
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
8 changes: 8 additions & 0 deletions docs/rules/no-constant-condition.md
Expand Up @@ -32,6 +32,14 @@ if (x &&= false) {
doSomethingNever();
}

if (class {}) {
doSomethingAlways();
}

if (new Boolean(x)) {
doSomethingAlways();
}

if (x ||= true) {
doSomethingAlways();
}
Expand Down
4 changes: 3 additions & 1 deletion lib/rules/no-constant-condition.js
Expand Up @@ -139,6 +139,7 @@ module.exports = {
case "ArrowFunctionExpression":
case "FunctionExpression":
case "ObjectExpression":
case "ClassExpression":
return true;
case "TemplateLiteral":
return (inBooleanPosition && node.quasis.some(quasi => quasi.value.cooked.length)) ||
Expand Down Expand Up @@ -180,7 +181,8 @@ module.exports = {
isLeftShortCircuit ||
isRightShortCircuit;
}

case "NewExpression":
return true;
case "AssignmentExpression":
if (node.operator === "=") {
return isConstant(node.right, inBooleanPosition);
Expand Down
12 changes: 11 additions & 1 deletion tests/lib/rules/no-constant-condition.js
Expand Up @@ -387,6 +387,16 @@ ruleTester.run("no-constant-condition", rule, {
{ code: "if(0b1n);", parserOptions: { ecmaVersion: 11 }, errors: [{ messageId: "unexpected", type: "Literal" }] },
{ code: "if(0o1n);", parserOptions: { ecmaVersion: 11 }, errors: [{ messageId: "unexpected", type: "Literal" }] },
{ code: "if(0x1n);", parserOptions: { ecmaVersion: 11 }, errors: [{ messageId: "unexpected", type: "Literal" }] },
{ code: "if(0x1n || foo);", parserOptions: { ecmaVersion: 11 }, errors: [{ messageId: "unexpected", type: "LogicalExpression" }] }
{ code: "if(0x1n || foo);", parserOptions: { ecmaVersion: 11 }, errors: [{ messageId: "unexpected", type: "LogicalExpression" }] },

// Classes and instances are always truthy
{ code: "if(class {}) {}", errors: [{ messageId: "unexpected" }] },
{ code: "if(new Foo()) {}", errors: [{ messageId: "unexpected" }] },

// Boxed primitives are always truthy
{ code: "if(new Boolean(foo)) {}", errors: [{ messageId: "unexpected" }] },
{ code: "if(new String(foo)) {}", errors: [{ messageId: "unexpected" }] },
{ code: "if(new Number(foo)) {}", errors: [{ messageId: "unexpected" }] }

]
});

0 comments on commit 286cf80

Please sign in to comment.