Skip to content

Commit 6e7a44c

Browse files
committed
feature: @putout/plugin-apply-shorthand-properties: computed
1 parent 2f5af3f commit 6e7a44c

File tree

4 files changed

+42
-11
lines changed

4 files changed

+42
-11
lines changed

packages/plugin-apply-shorthand-properties/lib/apply-shorthand-properties.js

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,15 @@
11
import {types, operator} from 'putout';
22

3-
const {findBinding, rename} = operator;
4-
const {isImportSpecifier} = types;
3+
const {
4+
findBinding,
5+
rename,
6+
replaceWith,
7+
} = operator;
8+
9+
const {
10+
isImportSpecifier,
11+
identifier,
12+
} = types;
513

614
export const report = () => `Use shorthand properties`;
715

@@ -15,6 +23,13 @@ export const fix = ({path, from, to, toRename}) => {
1523
rename(path, from, to);
1624

1725
path.node.shorthand = true;
26+
27+
const keyPath = path.get('key');
28+
29+
if (keyPath.isStringLiteral()) {
30+
replaceWith(keyPath, identifier(keyPath.node.value));
31+
path.node.computed = false;
32+
}
1833
};
1934

2035
export const traverse = ({push, options}) => ({
@@ -31,20 +46,20 @@ export const traverse = ({push, options}) => ({
3146
if (shorthand)
3247
continue;
3348

34-
if (computed)
35-
continue;
36-
3749
const valuePath = propPath.get('value');
3850
const keyPath = propPath.get('key');
3951

52+
if (computed && !keyPath.isStringLiteral())
53+
continue;
54+
55+
if (!computed && keyPath.isStringLiteral())
56+
continue;
57+
4058
const {rename, ignore = []} = options;
4159

4260
const from = getName(valuePath);
4361
const to = getName(keyPath);
4462

45-
if (!to)
46-
continue;
47-
4863
if (ignore.includes(from))
4964
continue;
5065

@@ -92,5 +107,8 @@ function getName(path) {
92107
if (path.isIdentifier())
93108
return node.name;
94109

110+
if (path.isStringLiteral())
111+
return node.value;
112+
95113
return '';
96114
}

packages/plugin-apply-shorthand-properties/test/apply-shorthand-properties.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,8 +104,8 @@ test('plugin-apply-shorthand-properties: no transform: import-declaration', (t)
104104
t.end();
105105
});
106106

107-
test('plugin-apply-shorthand-properties: no report: computed', (t) => {
108-
t.noReport('computed');
107+
test('plugin-apply-shorthand-properties: transform: computed', (t) => {
108+
t.transform('computed');
109109
t.end();
110110
});
111111

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
fn({
2+
x,
3+
'y': y,
4+
});
5+
6+
const a = {
7+
[hello]: hello,
8+
};
Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
fn({
2+
['x']: x,
3+
'y': y,
4+
});
5+
16
const a = {
27
[hello]: hello,
3-
}
8+
};

0 commit comments

Comments
 (0)