Skip to content

Commit

Permalink
Added Array.from unsafe optimization (#747)
Browse files Browse the repository at this point in the history
Closes #746
  • Loading branch information
L2jLiga committed Aug 24, 2021
1 parent f4a3ca4 commit d3fb5b0
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -1090,6 +1090,7 @@ You might want to try it on your own code; it should reduce the minified size.
Some examples of the optimizations made when this option is enabled:

- `new Array(1, 2, 3)` or `Array(1, 2, 3)``[ 1, 2, 3 ]`
- `Array.from([1, 2, 3])``[1, 2, 3]`
- `new Object()``{}`
- `String(exp)` or `exp.toString()``"" + exp`
- `new Object/RegExp/Function/Error/Array (...)` → we discard the `new`
Expand Down
8 changes: 8 additions & 0 deletions lib/compress/index.js
Expand Up @@ -2058,6 +2058,14 @@ def_optimize(AST_Call, function(self, compressor) {
}

if (compressor.option("unsafe")) {
if (exp instanceof AST_Dot && exp.start.value === "Array" && exp.property === "from" && self.args.length === 1) {
const [argument] = self.args;
if (argument instanceof AST_Array) {
return make_node(AST_Array, argument, {
elements: argument.elements
}).optimize(compressor);
}
}
if (is_undeclared_ref(exp)) switch (exp.name) {
case "Array":
if (self.args.length != 1) {
Expand Down
24 changes: 24 additions & 0 deletions test/compress/arrays.js
Expand Up @@ -314,3 +314,27 @@ index_length: {
}
expect_stdout: "1 2"
}

array_from: {
options = {
unsafe: true,
unused: true,
}
input: {
var a = Array.from([1]);
var b = Array.from([1], a => a);
var c = Array.from(1);
var d = Array.from("String");
var e = Array.from({ });
console.log(a[0], b[0], c, d[3], e);
}
expect: {
var a = [1];
var b = Array.from([1], a => a);
var c = Array.from(1);
var d = Array.from("String");
var e = Array.from({});
console.log(a[0], b[0], c, d[3], e);
}
expect_stdout: "1 1 [] i []"
}

0 comments on commit d3fb5b0

Please sign in to comment.