diff options
author | Alex Lam S.L <alexlamsl@gmail.com> | 2018-01-10 16:59:57 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-01-10 16:59:57 +0800 |
commit | 09269be9745ab269acaa320db0abaed67ca06566 (patch) | |
tree | 09ee60184e319f4d65410bee7d4e1a15a12b975e | |
parent | bf832cde167b6de119761d54302977e14b10c00b (diff) | |
download | tracifyjs-09269be9745ab269acaa320db0abaed67ca06566.tar.gz tracifyjs-09269be9745ab269acaa320db0abaed67ca06566.zip |
enhance `conditionals` (#2758)
`x ? y || z : z` --> `x && y || z`
-rw-r--r-- | lib/compress.js | 14 | ||||
-rw-r--r-- | test/compress/conditionals.js | 43 |
2 files changed, 57 insertions, 0 deletions
diff --git a/lib/compress.js b/lib/compress.js index 406a331c..9760c546 100644 --- a/lib/compress.js +++ b/lib/compress.js @@ -5278,6 +5278,20 @@ merge(Compressor.prototype, { consequent ]).optimize(compressor); } + // x ? y || z : z --> x && y || z + if (consequent instanceof AST_Binary + && consequent.operator == "||" + && consequent.right.equivalent_to(alternative)) { + return make_node(AST_Binary, self, { + operator: "||", + left: make_node(AST_Binary, self, { + operator: "&&", + left: self.condition, + right: consequent.left + }), + right: alternative + }).optimize(compressor); + } var in_bool = compressor.in_boolean_context(); if (is_true(self.consequent)) { if (is_false(self.alternative)) { diff --git a/test/compress/conditionals.js b/test/compress/conditionals.js index 7838fdbb..e37c5556 100644 --- a/test/compress/conditionals.js +++ b/test/compress/conditionals.js @@ -1224,3 +1224,46 @@ hoist_decl: { x() ? y() : z(); } } + +to_and_or: { + options = { + conditionals: true, + } + input: { + var values = [ + 0, + null, + true, + "foo", + false, + -1 / 0, + void 0, + ]; + values.forEach(function(x) { + values.forEach(function(y) { + values.forEach(function(z) { + console.log(x ? y || z : z); + }); + }); + }); + } + expect: { + var values = [ + 0, + null, + true, + "foo", + false, + -1 / 0, + void 0, + ]; + values.forEach(function(x) { + values.forEach(function(y) { + values.forEach(function(z) { + console.log(x && y || z); + }); + }); + }); + } + expect_stdout: true +} |