-
-
Notifications
You must be signed in to change notification settings - Fork 153
/
noMutableArray.js
65 lines (57 loc) · 1.77 KB
/
noMutableArray.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
import _ from 'lodash';
const schema = [];
// const x = [];
const isEmptyArrayLiteral = (node) => {
return _.get(node, 'init.type') === 'ArrayExpression' && _.get(node, 'init.elements.length') === 0;
};
// const x = new Array(); const y = Array();
const isEmptyArrayInstance = (node) => {
if (_.get(node, 'init.type') === 'NewExpression' || _.get(node, 'init.type') === 'CallExpression') {
return _.get(node, 'init.callee.name') === 'Array' && _.get(node, 'init.arguments.length') === 0;
} else {
return false;
}
};
const isAnnotationOfEmptyArrayInit = (node) => {
if (_.has(node, 'parent.parent.parent')) {
const parent = _.get(node, 'parent.parent.parent');
const isVariableDeclaration = _.get(parent, 'type') === 'VariableDeclarator';
return isVariableDeclaration && (isEmptyArrayLiteral(parent) || isEmptyArrayInstance(parent));
} else {
return false;
}
};
const create = (context) => {
return {
ArrayTypeAnnotation (node) {
if (!isAnnotationOfEmptyArrayInit(node)) {
context.report({
fix (fixer) {
const rawElementType = context.getSourceCode().getText(node.elementType);
return fixer.replaceText(node, '$ReadOnlyArray<' + rawElementType + '>');
},
message: 'Use "$ReadOnlyArray" instead of array shorthand notation',
node,
});
}
},
GenericTypeAnnotation (node) {
if (node.id.name === 'Array' && !isAnnotationOfEmptyArrayInit(node)) {
context.report({
fix (fixer) {
return fixer.replaceText(node.id, '$ReadOnlyArray');
},
message: 'Use "$ReadOnlyArray" instead of "Array"',
node,
});
}
},
};
};
export default {
create,
meta: {
fixable: 'code',
},
schema,
};