Compress conditions that have side effects using sequences
authorTal Ater <tal@talater.com>
Wed, 3 Sep 2014 23:57:49 +0000 (02:57 +0300)
committerTal Ater <tal@talater.com>
Wed, 3 Sep 2014 23:57:49 +0000 (02:57 +0300)
lib/compress.js
test/compress/conditionals.js

index e493e5f..77de594 100644 (file)
@@ -2322,11 +2322,15 @@ merge(Compressor.prototype, {
             });
         }
         // x=y?1:1 --> x=1
-        if (!self.condition.has_side_effects(compressor)
-            && consequent instanceof AST_Constant
+        if (consequent instanceof AST_Constant
             && alternative instanceof AST_Constant
             && consequent.equivalent_to(alternative)) {
-            return make_node_from_constant(compressor, consequent.value, self);
+            if (self.condition.has_side_effects(compressor)) {
+                return AST_Seq.from_array([self.condition, make_node_from_constant(compressor, consequent.value, self)]);
+            } else {
+                return make_node_from_constant(compressor, consequent.value, self);
+
+            }
         }
         return self;
     });
index c244dc8..c20297a 100644 (file)
@@ -258,30 +258,38 @@ cond_7: {
 
         x = y ? 'foo' : y ? 'foo' : 'fo'+'o';
 
-        // don't compress these
-        x = y ? a : b;
-
-        x = y ? 'foo' : 'fo';
+        // Compress conditions that have side effects
+        if (condition()) {
+            x = 10+10;
+        } else {
+            x = 20;
+        }
 
-        // make sure not to mess with conditions that have side effects
-        // TODO: Make sure to mess with conditions that have side effects... proprely
-        if (some_condition()) {
-            x = 1+1;
+        if (z) {
+            x = 'fuji';
+        } else if (condition()) {
+            x = 'fu'+'ji';
         } else {
-            x = 2;
+            x = 'fuji';
         }
 
-        x = some_condition() ? 'foo' : 'fo'+'o';
+        x = condition() ? 'foobar' : 'foo'+'bar';
+
+        // don't compress these
+        x = y ? a : b;
+
+        x = y ? 'foo' : 'fo';
     }
     expect: {
         x = 2;
         x = 2;
         x = 'foo';
         x = 'foo';
+        x = (condition(), 20);
+        x = z ? 'fuji' : (condition(), 'fuji');
+        x = (condition(), 'foobar');
         x = y ? a : b;
         x = y ? 'foo' : 'fo';
-        x = some_condition() ? 2 : 2;
-        x = some_condition() ? 'foo' : 'foo';
     }
 }