google / google/closure-compiler
Inline computed property names in object literals
- Dominant language
- JavaScript
- Stars
- 7.7k
- Forks
- 1.2k
- Avg merge
- 2d 12h
- Merged PRs (30d)
- 6
Description
Here's a potential improvement for ADVANCED_OPTIMIZATIONS. Given this JS:
```javascript
/**
* @enum {string} JSON keys used in my app.
*/
const KEYS = {
NAME: 'name',
AGE: 'age',
};
function getPersonStruct(name, age) {
return {
[KEYS.NAME]: name,
[KEYS.AGE]: age
};
}
console.log(getPersonStruct('Jane', 50));
```
Here's what the compiler currently generates:
```javascript
var a,b={};a=(b.name="Jane",b.age=50,b);console.log(a);
```
Here's the command I used to generate that:
```
java -jar closure-compiler-v20200406.jar \
--language_in ECMASCRIPT6 \
--language_out ECMASCRIPT5 \
--compilation_level ADVANCED_OPTIMIZATIONS \
keys_test.js
```
Given that the object keys in this example are constants, it would be nice to avoid the creation of these temporary variables `a` and `b`. The ideal output would be:
```javascript
console.log({"name": "Jane", "age": 50});
```
A specific use case: In my Closure Compiler-annotated JavaScript, I have an enum/constant that defines all JSON keys my app uses. This keeps things nicely defined in a single place, rather than scattering JSON keys all over the code base. In many cases, it's more convenient (and takes up less code) to create these JSON objects as JavaScript literals rather than creating an empty object and appending to it.
Contributor guide
Assessment
This issue has not been assessed yet.