-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathnormalizeComputed.js
56 lines (54 loc) · 2 KB
/
normalizeComputed.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
import {badIdentifierCharsRegex, validIdentifierBeginning} from '../config.js';
/**
* Change all member expressions and class methods which has a property which can support it - to non-computed.
* E.g.
* console['log'] -> console.log
* @param {Arborist} arb
* @param {Function} candidateFilter (optional) a filter to apply on the candidates list
* @return {Arborist}
*/
function normalizeComputed(arb, candidateFilter = () => true) {
const relevantNodes = [
...(arb.ast[0].typeMap.MemberExpression || []),
...(arb.ast[0].typeMap.MethodDefinition || []),
...(arb.ast[0].typeMap.Property || []),
];
for (let i = 0; i < relevantNodes.length; i++) {
const n = relevantNodes[i];
if (n.computed && // Filter for only member expressions using bracket notation
// Ignore member expressions with properties which can't be non-computed, like arr[2] or window['!obj']
// or those having another variable reference as their property like window[varHoldingFuncName]
(n.type === 'MemberExpression' &&
n.property.type === 'Literal' &&
validIdentifierBeginning.test(n.property.value) &&
!badIdentifierCharsRegex.test(n.property.value)) ||
/**
* Ignore the same cases for method names and object properties, for example
* class A {
* ['!hello']() {} // Can't change the name of this method
* ['miao']() {} // This can be changed to 'miao() {}'
* }
* const obj = {
* ['!hello']: 1, // Will be ignored
* ['miao']: 4 // Will be changed to 'miao: 4'
* };
*/
(['MethodDefinition', 'Property'].includes(n.type) &&
n.key.type === 'Literal' &&
validIdentifierBeginning.test(n.key.value) &&
!badIdentifierCharsRegex.test(n.key.value)) &&
candidateFilter(n)) {
const relevantProperty = n.type === 'MemberExpression' ? 'property' : 'key';
arb.markNode(n, {
...n,
computed: false,
[relevantProperty]: {
type: 'Identifier',
name: n[relevantProperty].value,
},
});
}
}
return arb;
}
export default normalizeComputed;