Skip to content

Commit fdc9b94

Browse files
authoredMar 2, 2017
minor improvement to string optimisation (#1514)
- "" + "a" => "a" - "" + a + "b" => a + "b" - "a" + "" => "a" (improving on #45)
1 parent 40ceddb commit fdc9b94

File tree

2 files changed

+69
-10
lines changed

2 files changed

+69
-10
lines changed
 

‎lib/compress.js

+19-10
Original file line numberDiff line numberDiff line change
@@ -1054,12 +1054,6 @@ merge(Compressor.prototype, {
10541054
def(AST_Conditional, function(compressor){
10551055
return this.consequent.is_string(compressor) && this.alternative.is_string(compressor);
10561056
});
1057-
def(AST_Call, function(compressor){
1058-
return compressor.option("unsafe")
1059-
&& this.expression instanceof AST_SymbolRef
1060-
&& this.expression.name == "String"
1061-
&& this.expression.undeclared();
1062-
});
10631057
})(function(node, func){
10641058
node.DEFMETHOD("is_string", func);
10651059
});
@@ -2985,10 +2979,25 @@ merge(Compressor.prototype, {
29852979
}
29862980
}
29872981
}
2988-
if (self.operator == "+" && self.right instanceof AST_String
2989-
&& self.right.getValue() === "" && self.left instanceof AST_Binary
2990-
&& self.left.operator == "+" && self.left.is_string(compressor)) {
2991-
return self.left;
2982+
if (self.operator == "+") {
2983+
if (self.right instanceof AST_String
2984+
&& self.right.getValue() == ""
2985+
&& self.left.is_string(compressor)) {
2986+
return self.left;
2987+
}
2988+
if (self.left instanceof AST_String
2989+
&& self.left.getValue() == ""
2990+
&& self.right.is_string(compressor)) {
2991+
return self.right;
2992+
}
2993+
if (self.left instanceof AST_Binary
2994+
&& self.left.operator == "+"
2995+
&& self.left.left instanceof AST_String
2996+
&& self.left.left.getValue() == ""
2997+
&& self.right.is_string(compressor)) {
2998+
self.left = self.left.right;
2999+
return self.transform(compressor);
3000+
}
29923001
}
29933002
if (compressor.option("evaluate")) {
29943003
switch (self.operator) {

‎test/compress/concat-strings.js

+50
Original file line numberDiff line numberDiff line change
@@ -164,3 +164,53 @@ concat_6: {
164164
);
165165
}
166166
}
167+
168+
concat_7: {
169+
input: {
170+
console.log(
171+
"" + 1,
172+
"" + "1",
173+
"" + 1 + 2,
174+
"" + 1 + "2",
175+
"" + "1" + 2,
176+
"" + "1" + "2",
177+
"" + (x += "foo")
178+
);
179+
}
180+
expect: {
181+
console.log(
182+
"" + 1,
183+
"1",
184+
"" + 1 + 2,
185+
1 + "2",
186+
"1" + 2,
187+
"1" + "2",
188+
x += "foo"
189+
);
190+
}
191+
}
192+
193+
concat_8: {
194+
input: {
195+
console.log(
196+
1 + "",
197+
"1" + "",
198+
1 + 2 + "",
199+
1 + "2" + "",
200+
"1" + 2 + "",
201+
"1" + "2" + "",
202+
(x += "foo") + ""
203+
);
204+
}
205+
expect: {
206+
console.log(
207+
1 + "",
208+
"1",
209+
1 + 2 + "",
210+
1 + "2",
211+
"1" + 2,
212+
"1" + "2",
213+
x += "foo"
214+
);
215+
}
216+
}

0 commit comments

Comments
 (0)
Please sign in to comment.