-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
81 lines (73 loc) · 2.1 KB
/
index.js
File metadata and controls
81 lines (73 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/** @type {import('eslint').Rule.RuleModule} */
export default {
meta: {
docs: {
description:
'Prefer early returns over full-body conditional wrapping in function declarations.',
category: 'Best Practices',
recommended: false,
uri: 'https://github.com/cloudfour/eslint-config/blob/main/src/rules/prefer-early-return/README.md',
},
schema: [
{
type: 'object',
properties: {
maximumStatements: {
type: 'integer',
},
},
additionalProperties: false,
},
],
},
create(context) {
const options = context.options[0] || { maximumStatements: 2 };
const maxStatements = options.maximumStatements;
/** @param {import('estree').Statement} consequent */
function isOffendingConsequent(consequent) {
return (
(consequent.type === 'ExpressionStatement' && maxStatements === 0) ||
(consequent.type === 'BlockStatement' &&
consequent.body.length > maxStatements)
);
}
/** @param {import('estree').Statement} statement */
function isOffendingIfStatement(statement) {
return (
isLonelyIfStatement(statement) &&
isOffendingConsequent(statement.consequent)
);
}
/** @param {import('estree').BlockStatement} functionBody */
function hasSimplifiableConditionalBody(functionBody) {
const body = functionBody.body;
return (
functionBody.type === 'BlockStatement' &&
body.length === 1 &&
isOffendingIfStatement(body[0])
);
}
/** @param {import('estree').FunctionDeclaration} functionNode */
function checkFunctionBody(functionNode) {
const body = functionNode.body;
if (hasSimplifiableConditionalBody(body)) {
context.report(
body,
'Prefer an early return to a conditionally-wrapped function body',
);
}
}
return {
FunctionDeclaration: checkFunctionBody,
FunctionExpression: checkFunctionBody,
ArrowFunctionExpression: checkFunctionBody,
};
},
};
/**
* @param {import('estree').Statement} statement
* @returns {statement is import('estree').IfStatement}
*/
function isLonelyIfStatement(statement) {
return statement.type === 'IfStatement' && statement.alternate === null;
}