Skip to content

Commit

Permalink
Fix: no-constant-condition doesn't introspect arrays (fixes #12225)
Browse files Browse the repository at this point in the history
  • Loading branch information
Sean Gray authored and tickct committed Sep 24, 2019
1 parent f9fc695 commit b146b51
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
16 changes: 15 additions & 1 deletion lib/rules/no-constant-condition.js
Expand Up @@ -90,14 +90,28 @@ module.exports = {
* @private
*/
function isConstant(node, inBooleanPosition) {

/*
* Bug in espree (#425) causes [,] to return children of null
* so we need to check for existance until that is fixed
*/
if (!node) {
return true;
}
switch (node.type) {
case "Literal":
case "ArrowFunctionExpression":
case "FunctionExpression":
case "ObjectExpression":
case "ArrayExpression":
return true;

case "ArrayExpression": {
if (inBooleanPosition) {
return true;
}
return node.elements.every(element => isConstant(element, false));
}

case "UnaryExpression":
if (node.operator === "void") {
return true;
Expand Down
26 changes: 26 additions & 0 deletions tests/lib/rules/no-constant-condition.js
Expand Up @@ -73,6 +73,14 @@ ruleTester.run("no-constant-condition", rule, {
"if ((key || 'k') in obj) {}",
"if ((foo || {}) instanceof obj) {}",

// #12225
"if ('' + [y] === '' + [ty]) {}",
"if ('a' === '' + [ty]) {}",
"if ('' + [y, m, d] === 'a') {}",
"if ('' + [y, 'm'] === '' + [ty, 'tm']) {}",
"if ('' + [y, 'm'] === '' + ['ty']) {}",
"if ([,] in\n\n($2))\n ;\nelse\n ;",

// { checkLoops: false }
{ code: "while(true);", options: [{ checkLoops: false }] },
{ code: "for(;true;);", options: [{ checkLoops: false }] },
Expand Down Expand Up @@ -183,6 +191,24 @@ ruleTester.run("no-constant-condition", rule, {
{
code: "function* foo() { for (let foo = 1 + 2 + 3 + (yield); true; baz) {}}",
errors: [{ messageId: "unexpected", type: "Literal" }]
},

// #12225
{
code: "if([a]) {}",
errors: [{ messageId: "unexpected", type: "ArrayExpression" }]
},
{
code: "if([]) {}",
errors: [{ messageId: "unexpected", type: "ArrayExpression" }]
},
{
code: "if(''+['a']) {}",
errors: [{ messageId: "unexpected", type: "BinaryExpression" }]
},
{
code: "if(''+[]) {}",
errors: [{ messageId: "unexpected", type: "BinaryExpression" }]
}
]
});

0 comments on commit b146b51

Please sign in to comment.