Skip to content

Commit

Permalink
Fix: no-else-return false positive for ifs in single-statement positi…
Browse files Browse the repository at this point in the history
…on (#8338)

Fixing errors from no-else-return requires splitting a single statement into two statements. This means that there is no reasonable fix for the errors when the if statement is in a position where only a single statement is allowed, so the rule should not report this case.
  • Loading branch information
not-an-aardvark authored and gyandeeps committed Mar 27, 2017
1 parent 6a718ba commit d064ba2
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
9 changes: 6 additions & 3 deletions lib/rules/no-else-return.js
Expand Up @@ -9,6 +9,7 @@
// Requirements
//------------------------------------------------------------------------------

const astUtils = require("../ast-utils");
const FixTracker = require("../util/fix-tracker");

//------------------------------------------------------------------------------
Expand Down Expand Up @@ -199,9 +200,11 @@ module.exports = {
let consequents,
alternate;

// Only "top-level" if statements are checked, meaning the first `if`
// in a `if-else-if-...` chain.
if (parent.type === "IfStatement" && parent.alternate === node) {
/*
* Fixing this would require splitting one statement into two, so no error should
* be reported if this node is in a position where only one statement is allowed.
*/
if (!astUtils.STATEMENT_LIST_PARENTS.has(parent.type)) {
return;
}

Expand Down
17 changes: 16 additions & 1 deletion tests/lib/rules/no-else-return.js
Expand Up @@ -27,7 +27,22 @@ ruleTester.run("no-else-return", rule, {
"function foo() { if (true) notAReturn(); else return y; }",
"function foo() {if (x) { notAReturn(); } else if (y) { return true; } else { notAReturn(); } }",
"function foo() {if (x) { return true; } else if (y) { notAReturn() } else { notAReturn(); } }",
"if (0) { if (0) {} else {} } else {}"
"if (0) { if (0) {} else {} } else {}",
`
function foo() {
if (foo)
if (bar) return;
else baz;
else qux;
}
`,
`
function foo() {
while (foo)
if (bar) return;
else baz;
}
`
],
invalid: [
{
Expand Down

0 comments on commit d064ba2

Please sign in to comment.