Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 18 additions & 8 deletions packages/eslint-plugin/lib/rules/prefer-early-return.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,20 +50,20 @@ module.exports = {
}

function hasSimplifiableConditionalBody(functionBody) {
const body = functionBody.body;
return (
functionBody.type === 'BlockStatement' &&
body.length === 1 &&
isOffendingIfStatement(body[0])
);
if (!isBlockStatement(functionBody)) {
return false;
}

const lastStatement = getLastStatement(functionBody);
return Boolean(lastStatement) && isOffendingIfStatement(lastStatement);
}

function checkFunctionBody(functionNode) {
const body = functionNode.body;

if (hasSimplifiableConditionalBody(body)) {
if (isBlockStatement(body) && hasSimplifiableConditionalBody(body)) {
context.report(
body,
getLastStatement(body),
'Prefer an early return to a conditionally-wrapped function body',
);
}
Expand All @@ -76,3 +76,13 @@ module.exports = {
};
},
};

function getLastStatement(statement) {
return 'body' in statement && statement.body.length > 0
? statement.body[statement.body.length - 1]
: undefined;
}

function isBlockStatement(statement) {
return statement?.type === 'BlockStatement';
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const ruleTester = new RuleTester();

const error = {
message: 'Prefer an early return to a conditionally-wrapped function body',
type: 'BlockStatement',
type: 'IfStatement',
};

ruleTester.run('prefer-early-return', rule, {
Expand Down Expand Up @@ -144,5 +144,15 @@ ruleTester.run('prefer-early-return', rule, {
})`,
errors: [error],
},
{
code: `function foo() {
var bool = a && b;
if (bool) {
doSomething();
doSomethingElse();
}
}`,
errors: [error],
},
],
});