Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

array literal initializers, index assignments, aren't optimized #5790

Closed
bulk88 opened this issue Apr 7, 2023 · 1 comment · Fixed by #5824
Closed

array literal initializers, index assignments, aren't optimized #5790

bulk88 opened this issue Apr 7, 2023 · 1 comment · Fixed by #5824

Comments

@bulk88
Copy link

bulk88 commented Apr 7, 2023

uglify-js 3.17.4

input

(function() {
var a = [];
a[0] = 1;
a[1] = 2;
a[2] = 3;
console.log(a);
})() 

commandline

uglifyjs --config-file u.json status.js

config

{
    "compress": {
      "inline": true,
      "passes": 3,
      "reduce_funcs": true,
      "reduce_vars": true,
      "side_effects": true,
      "toplevel": true,
      "unsafe": true,
      "unused": true
    },
    "ie": true,
    "mangle": {
      "eval": true,
      "reserved": ["x", "y"],
      "toplevel": true
    },
    "nameCache": {}
  }

output

var o;(o=[])[0]=1,o[1]=2,o[2]=3,console.log(o);

Why wasn't this optimized to

console.log([1,2,3])

?

My goal is to use an ARRAY indexed JSON storage schema instead of object keys, to save space in the JSON string. I'd rather not do this optimization by hand writing array literals with heavy comments.

(function() {
function NAME () {return 0;}
function ADDRESS() {return 1;}
function TELEPHONE() {return 2;}
var a = [];
a[NAME()] = 1;
a[ADDRESS()] = 2;
a[TELEPHONE()] = 3;
console.log(a);
})()
 ```

@alexlamsl
Copy link
Collaborator

alexlamsl commented Jun 3, 2024

uglify-js supports what you suggested via join_vars, but only towards objects:

require('uglify-js').minify(`
(function() {
function NAME () {return 0;}
function ADDRESS() {return 1;}
function TELEPHONE() {return 2;}
var a = {};
a[NAME()] = 1;
a[ADDRESS()] = 2;
a[TELEPHONE()] = 3;
console.log(a);
})()
`, {
    compress: {
        passes: 2,
    },
    output: {
        beautify: true,
    },
}).code;

gives:

console.log({
    0: 1,
    1: 2,
    2: 3
});

I guess there's no harm extending it towards arrays as well.

alexlamsl added a commit to alexlamsl/UglifyJS that referenced this issue Jun 3, 2024
alexlamsl added a commit to alexlamsl/UglifyJS that referenced this issue Jun 5, 2024
alexlamsl added a commit that referenced this issue Jun 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants