/
default-param-last.ts
81 lines (75 loc) · 2.08 KB
/
default-param-last.ts
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
import { createRule } from '../util';
import {
TSESTree,
AST_NODE_TYPES,
} from '@typescript-eslint/experimental-utils';
export default createRule({
name: 'default-param-last',
meta: {
type: 'suggestion',
docs: {
description: 'Enforce default parameters to be last',
category: 'Best Practices',
recommended: false,
extendsBaseRule: true,
},
schema: [],
messages: {
shouldBeLast: 'Default parameters should be last.',
},
},
defaultOptions: [],
create(context) {
/**
* checks if node is optional parameter
* @param node the node to be evaluated
* @private
*/
function isOptionalParam(node: TSESTree.Parameter): boolean {
return 'optional' in node && node.optional === true;
}
/**
* checks if node is plain parameter
* @param node the node to be evaluated
* @private
*/
function isPlainParam(node: TSESTree.Parameter): boolean {
return !(
node.type === AST_NODE_TYPES.AssignmentPattern ||
node.type === AST_NODE_TYPES.RestElement ||
isOptionalParam(node)
);
}
function checkDefaultParamLast(
node:
| TSESTree.ArrowFunctionExpression
| TSESTree.FunctionDeclaration
| TSESTree.FunctionExpression,
): void {
let hasSeenPlainParam = false;
for (let i = node.params.length - 1; i >= 0; i--) {
const current = node.params[i];
const param =
current.type === AST_NODE_TYPES.TSParameterProperty
? current.parameter
: current;
if (isPlainParam(param)) {
hasSeenPlainParam = true;
continue;
}
if (
hasSeenPlainParam &&
(isOptionalParam(param) ||
param.type === AST_NODE_TYPES.AssignmentPattern)
) {
context.report({ node: current, messageId: 'shouldBeLast' });
}
}
}
return {
ArrowFunctionExpression: checkDefaultParamLast,
FunctionDeclaration: checkDefaultParamLast,
FunctionExpression: checkDefaultParamLast,
};
},
});