-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
no-dynamic-delete.ts
103 lines (91 loc) · 2.53 KB
/
no-dynamic-delete.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import {
TSESTree,
AST_NODE_TYPES,
TSESLint,
} from '@typescript-eslint/experimental-utils';
import * as tsutils from 'tsutils';
import * as util from '../util';
export default util.createRule({
name: 'no-dynamic-delete',
meta: {
docs: {
description: 'Disallow the delete operator with computed key expressions',
recommended: false,
},
fixable: 'code',
messages: {
dynamicDelete: 'Do not delete dynamically computed property keys.',
},
schema: [],
type: 'suggestion',
},
defaultOptions: [],
create(context) {
function createFixer(
member: TSESTree.MemberExpression,
): TSESLint.ReportFixFunction | undefined {
if (
member.property.type === AST_NODE_TYPES.Literal &&
typeof member.property.value === 'string'
) {
return createPropertyReplacement(
member.property,
`.${member.property.value}`,
);
}
return undefined;
}
return {
'UnaryExpression[operator=delete]'(node: TSESTree.UnaryExpression): void {
if (
node.argument.type !== AST_NODE_TYPES.MemberExpression ||
!node.argument.computed ||
isNecessaryDynamicAccess(
diveIntoWrapperExpressions(node.argument.property),
)
) {
return;
}
context.report({
fix: createFixer(node.argument),
messageId: 'dynamicDelete',
node: node.argument.property,
});
},
};
function createPropertyReplacement(
property: TSESTree.Expression,
replacement: string,
) {
return (fixer: TSESLint.RuleFixer): TSESLint.RuleFix =>
fixer.replaceTextRange(getTokenRange(property), replacement);
}
function getTokenRange(property: TSESTree.Expression): [number, number] {
const sourceCode = context.getSourceCode();
return [
sourceCode.getTokenBefore(property)!.range[0],
sourceCode.getTokenAfter(property)!.range[1],
];
}
},
});
function diveIntoWrapperExpressions(
node: TSESTree.Expression,
): TSESTree.Expression {
if (node.type === AST_NODE_TYPES.UnaryExpression) {
return diveIntoWrapperExpressions(node.argument);
}
return node;
}
function isNecessaryDynamicAccess(property: TSESTree.Expression): boolean {
if (property.type !== AST_NODE_TYPES.Literal) {
return false;
}
if (typeof property.value === 'number') {
return true;
}
return (
typeof property.value === 'string' &&
!tsutils.isValidPropertyAccess(property.value)
);
}