-
-
Notifications
You must be signed in to change notification settings - Fork 225
/
index.js
48 lines (42 loc) · 1.11 KB
/
index.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
"use strict";
const esutils = require("esutils");
module.exports = function({ types: t }) {
return {
name: "transform-property-literals",
visitor: {
// { 'foo': 'bar' } -> { foo: 'bar' }
ObjectProperty: {
exit({ node }) {
const key = node.key;
if (!t.isStringLiteral(key)) {
return;
}
if (key.value.match(/^\d+$/)) {
const newProp = parseInt(node.key.value, 10);
if (newProp.toString() === node.key.value) {
node.key = t.numericLiteral(newProp);
node.computed = false;
}
} else if (isValidPropertyName(key.value)) {
node.key = t.identifier(key.value);
node.computed = false;
}
}
}
}
};
};
// This currently targets es5 now.
// TODO:
// Target es6 after integration with babel-preset-env
function isValidPropertyName(name) {
if (typeof name !== "string") {
return false;
}
for (const char of name) {
if (!esutils.code.isIdentifierPartES5(char.charCodeAt(0))) {
return false;
}
}
return true;
}