|
| 1 | +/** |
| 2 | + * Adapted from https://github.com/Shopify/web-configs/blob/84c180fb08968276198faade21fa6918b104804c/packages/eslint-plugin/lib/rules/prefer-early-return.js#L1-L78 |
| 3 | + */ |
| 4 | +const defaultMaximumStatements = 0; |
| 5 | +const message = require('./CONST').MESSAGE.PREFER_EARLY_RETURN; |
| 6 | + |
| 7 | +module.exports = { |
| 8 | + create(context) { |
| 9 | + const options = context.options[0] || { |
| 10 | + maximumStatements: defaultMaximumStatements, |
| 11 | + }; |
| 12 | + const maxStatements = options.maximumStatements; |
| 13 | + |
| 14 | + function isLonelyIfStatement(statement) { |
| 15 | + return statement.type === 'IfStatement' && statement.alternate == null; |
| 16 | + } |
| 17 | + |
| 18 | + function isOffendingConsequent(consequent) { |
| 19 | + return ( |
| 20 | + (consequent.type === 'ExpressionStatement' && maxStatements === 0) |
| 21 | + || (consequent.type === 'BlockStatement' |
| 22 | + && consequent.body.length > maxStatements) |
| 23 | + ); |
| 24 | + } |
| 25 | + |
| 26 | + function isOffendingIfStatement(statement) { |
| 27 | + return ( |
| 28 | + isLonelyIfStatement(statement) |
| 29 | + && isOffendingConsequent(statement.consequent) |
| 30 | + ); |
| 31 | + } |
| 32 | + |
| 33 | + function hasSimplifiableConditionalBody(functionBody) { |
| 34 | + const body = functionBody.body; |
| 35 | + return ( |
| 36 | + functionBody.type === 'BlockStatement' |
| 37 | + && body.length === 1 |
| 38 | + && isOffendingIfStatement(body[0]) |
| 39 | + ); |
| 40 | + } |
| 41 | + |
| 42 | + function checkFunctionBody(functionNode) { |
| 43 | + const body = functionNode.body; |
| 44 | + |
| 45 | + if (hasSimplifiableConditionalBody(body)) { |
| 46 | + context.report( |
| 47 | + body, |
| 48 | + message, |
| 49 | + ); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + return { |
| 54 | + FunctionDeclaration: checkFunctionBody, |
| 55 | + FunctionExpression: checkFunctionBody, |
| 56 | + ArrowFunctionExpression: checkFunctionBody, |
| 57 | + }; |
| 58 | + }, |
| 59 | +}; |
0 commit comments