From c662ff0eb57d396e4cebd55ae08cbe50b1a97c31 Mon Sep 17 00:00:00 2001 From: Tal Ater Date: Sat, 13 Sep 2014 18:59:19 +0300 Subject: [PATCH] Optimize conditionals where the condition and consequent are equivalent and have no side effects --- lib/compress.js | 9 +++++++++ test/compress/conditionals.js | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/lib/compress.js b/lib/compress.js index 77de5946..f6177743 100644 --- a/lib/compress.js +++ b/lib/compress.js @@ -2332,6 +2332,15 @@ merge(Compressor.prototype, { } } + // x=y?y:z --> x=y||z + if (self.condition.equivalent_to(consequent) + && !self.condition.has_side_effects(compressor)) { + return make_node(AST_Binary, self.condition, { + left: self.condition, + operator: "||", + right: alternative + }); + } return self; }); diff --git a/test/compress/conditionals.js b/test/compress/conditionals.js index c20297aa..ab4f2512 100644 --- a/test/compress/conditionals.js +++ b/test/compress/conditionals.js @@ -293,3 +293,38 @@ cond_7: { } } +cond_8: { + options = { + conditionals: true, + evaluate : true + }; + input: { + // compress these + a = condition ? condition : b; + + if (condition) { + a = condition; + } else { + a = b; + } + + a = condition ? condition : b(); + + // Don't compress conditions that have side effects + if (condition()) { + a = condition(); + } else { + a = b; + } + + a = condition() ? condition() : b; + + } + expect: { + a = condition || b; + a = condition || b; + a = condition || b(); + a = condition() ? condition() : b; + a = condition() ? condition() : b; + } +} \ No newline at end of file