/
no-array-constructor.ts
63 lines (60 loc) · 1.6 KB
/
no-array-constructor.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
import {
TSESTree,
AST_NODE_TYPES,
} from '@typescript-eslint/experimental-utils';
import * as util from '../util';
export default util.createRule({
name: 'no-array-constructor',
meta: {
type: 'suggestion',
docs: {
description: 'Disallow generic `Array` constructors',
category: 'Stylistic Issues',
recommended: 'error',
extendsBaseRule: true,
},
fixable: 'code',
messages: {
useLiteral: 'The array literal notation [] is preferable.',
},
schema: [],
},
defaultOptions: [],
create(context) {
/**
* Disallow construction of dense arrays using the Array constructor
* @param node node to evaluate
*/
function check(
node: TSESTree.CallExpression | TSESTree.NewExpression,
): void {
if (
node.arguments.length !== 1 &&
node.callee.type === AST_NODE_TYPES.Identifier &&
node.callee.name === 'Array' &&
!node.typeParameters &&
!util.isOptionalCallExpression(node)
) {
context.report({
node,
messageId: 'useLiteral',
fix(fixer) {
if (node.arguments.length === 0) {
return fixer.replaceText(node, '[]');
}
const fullText = context.getSourceCode().getText(node);
const preambleLength = node.callee.range[1] - node.range[0];
return fixer.replaceText(
node,
`[${fullText.slice(preambleLength + 1, -1)}]`,
);
},
});
}
}
return {
CallExpression: check,
NewExpression: check,
};
},
});