-
Notifications
You must be signed in to change notification settings - Fork 109
/
object-shorthand.js
78 lines (71 loc) · 1.89 KB
/
object-shorthand.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
/**
* Simplifies object properties in object literals to use ES6 shorthand notation.
*
* This handles properties and methods, as well as properties which use literals as keys.
*
* e.g.
*
* var object = {
* identifier: identifier,
* 'identifier2': identifier2,
* method: function() {}
* }
*
* becomes:
*
* var object = {
* identifier,
* identifier2,
* method() {}
* }
*/
module.exports = (file, api, options) => {
const j = api.jscodeshift;
const printOptions = options.printOptions || {quote: 'single'};
const root = j(file.source);
const isRecursive = (value) => {
return !!(
value.id &&
j(value.body).find(j.Identifier).filter(
i => i.node.name === value.id.name
).size() !== 0
);
};
const canBeSimplified = (key, value) => {
// Can be simplified if both key and value are the same identifier or if the
// property is a method that is not recursive
if (key.type === 'Identifier') {
return (
value.type === 'Identifier' &&
key.name === value.name
) || (
value.type === 'FunctionExpression' &&
!isRecursive(value)
);
}
// Can be simplified if the key is a string literal which is equal to the
// identifier name of the value.
if (key.type === 'Literal') {
return value.type === 'Identifier' && key.value === value.name;
}
return false;
};
root
.find(j.Property, {
method: false,
shorthand: false,
computed: false,
})
.filter(p => canBeSimplified(p.value.key, p.value.value))
.forEach(p => {
if (p.value.key.type === 'Literal') {
p.value.key = p.value.value;
}
if (p.value.value.type === 'Identifier') {
p.value.shorthand = true;
} else if (p.value.value.type === 'FunctionExpression') {
p.value.method = true;
}
});
return root.toSource(printOptions);
};