/
no-new-array.js
98 lines (86 loc) · 2.39 KB
/
no-new-array.js
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
'use strict';
const {isParenthesized, getStaticValue} = require('eslint-utils');
const needsSemicolon = require('./utils/needs-semicolon.js');
const {newExpressionSelector} = require('./selectors/index.js');
const MESSAGE_ID_ERROR = 'error';
const MESSAGE_ID_LENGTH = 'array-length';
const MESSAGE_ID_ONLY_ELEMENT = 'only-element';
const MESSAGE_ID_SPREAD = 'spread';
const messages = {
[MESSAGE_ID_ERROR]: 'Do not use `new Array()`.',
[MESSAGE_ID_LENGTH]: 'The argument is the length of array.',
[MESSAGE_ID_ONLY_ELEMENT]: 'The argument is the only element of array.',
[MESSAGE_ID_SPREAD]: 'Spread the argument.',
};
const newArraySelector = newExpressionSelector({
name: 'Array',
argumentsLength: 1,
allowSpreadElement: true,
});
function getProblem(context, node) {
const problem = {
node,
messageId: MESSAGE_ID_ERROR,
};
const [argumentNode] = node.arguments;
const sourceCode = context.getSourceCode();
let text = sourceCode.getText(argumentNode);
if (isParenthesized(argumentNode, sourceCode)) {
text = `(${text})`;
}
const maybeSemiColon = needsSemicolon(sourceCode.getTokenBefore(node), sourceCode, '[')
? ';'
: '';
// We are not sure how many `arguments` passed
if (argumentNode.type === 'SpreadElement') {
problem.suggest = [
{
messageId: MESSAGE_ID_SPREAD,
fix: fixer => fixer.replaceText(node, `${maybeSemiColon}[${text}]`),
},
];
return problem;
}
const result = getStaticValue(argumentNode, context.getScope());
const fromLengthText = `Array.from(${text === 'length' ? '{length}' : `{length: ${text}}`})`;
const onlyElementText = `${maybeSemiColon}[${text}]`;
// We don't know the argument is number or not
if (result === null) {
problem.suggest = [
{
messageId: MESSAGE_ID_LENGTH,
fix: fixer => fixer.replaceText(node, fromLengthText),
},
{
messageId: MESSAGE_ID_ONLY_ELEMENT,
fix: fixer => fixer.replaceText(node, onlyElementText),
},
];
return problem;
}
problem.fix = fixer => fixer.replaceText(
node,
typeof result.value === 'number' ? fromLengthText : onlyElementText,
);
return problem;
}
const create = context => ({
[newArraySelector](node) {
return getProblem(context, node);
},
});
/**
* @type {import('eslint').Rule.RuleModule}
*/
module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
description: 'Disallow `new Array()`.',
},
fixable: 'code',
hasSuggestions: true,
messages,
},
};