From d3fb5b03c03ed060ac72fe8ef2db6c991af080cb Mon Sep 17 00:00:00 2001 From: Andrey Chalkin Date: Wed, 25 Aug 2021 06:10:31 +0700 Subject: [PATCH] Added Array.from unsafe optimization (#747) Closes #746 --- README.md | 1 + lib/compress/index.js | 8 ++++++++ test/compress/arrays.js | 24 ++++++++++++++++++++++++ 3 files changed, 33 insertions(+) diff --git a/README.md b/README.md index aa851a1ce..03ac40fdf 100644 --- a/README.md +++ b/README.md @@ -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` diff --git a/lib/compress/index.js b/lib/compress/index.js index 311a95204..aba660c72 100644 --- a/lib/compress/index.js +++ b/lib/compress/index.js @@ -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) { diff --git a/test/compress/arrays.js b/test/compress/arrays.js index 7e5c91a0c..757518a69 100644 --- a/test/compress/arrays.js +++ b/test/compress/arrays.js @@ -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 []" +}