From 4ae15df042081c3dbd05c87bb649369401aa369f Mon Sep 17 00:00:00 2001 From: camc314 <18101008+camc314@users.noreply.github.com> Date: Wed, 1 Jan 2025 02:31:18 +0000 Subject: [PATCH] feat(minifier): imprve more conditional expr minification with boolean lit (#8208) --- .../peephole_minimize_conditions.rs | 25 ++++++++++++++++++- tasks/minsize/minsize.snap | 6 ++--- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/crates/oxc_minifier/src/ast_passes/peephole_minimize_conditions.rs b/crates/oxc_minifier/src/ast_passes/peephole_minimize_conditions.rs index 1544a1f790380..1bcff47b4402e 100644 --- a/crates/oxc_minifier/src/ast_passes/peephole_minimize_conditions.rs +++ b/crates/oxc_minifier/src/ast_passes/peephole_minimize_conditions.rs @@ -341,6 +341,29 @@ impl<'a> PeepholeMinimizeConditions { )); } + // `x ? y : true` -> `!x || y` + // `x ? y : false` -> `x && y` + if let (Expression::Identifier(_), _, Expression::BooleanLiteral(alternate_lit)) = + (&expr.test, &expr.consequent, &expr.alternate) + { + if alternate_lit.value { + let ident = ctx.ast.move_expression(&mut expr.test); + return Some(ctx.ast.expression_logical( + expr.span, + ctx.ast.expression_unary(expr.span, UnaryOperator::LogicalNot, ident), + LogicalOperator::Or, + ctx.ast.move_expression(&mut expr.consequent), + )); + } + let ident = ctx.ast.move_expression(&mut expr.test); + return Some(ctx.ast.expression_logical( + expr.span, + ident, + LogicalOperator::And, + ctx.ast.move_expression(&mut expr.consequent), + )); + } + None } } @@ -645,7 +668,7 @@ mod test { fold("(x ? true : false) && y()", "!!x && y()"); fold("(x ? false : true) && y()", "!x && y()"); fold("(x ? true : y) && y()", "(x || y) && y()"); - // fold("(x ? y : false) && y()", "(x && y) && y()"); + fold("(x ? y : false) && y()", "(x && y) && y()"); // fold("(x && true) && y()", "x && y()"); // fold("(x && false) && y()", "0&&y()"); // fold("(x || true) && y()", "1&&y()"); diff --git a/tasks/minsize/minsize.snap b/tasks/minsize/minsize.snap index 9514b5486287f..0dc9af622eab3 100644 --- a/tasks/minsize/minsize.snap +++ b/tasks/minsize/minsize.snap @@ -13,7 +13,7 @@ Original | minified | minified | gzip | gzip | Fixture 555.77 kB | 273.48 kB | 270.13 kB | 90.94 kB | 90.80 kB | d3.js -1.01 MB | 460.75 kB | 458.89 kB | 126.87 kB | 126.71 kB | bundle.min.js +1.01 MB | 460.75 kB | 458.89 kB | 126.88 kB | 126.71 kB | bundle.min.js 1.25 MB | 653.17 kB | 646.76 kB | 163.58 kB | 163.73 kB | three.js @@ -21,7 +21,7 @@ Original | minified | minified | gzip | gzip | Fixture 3.20 MB | 1.01 MB | 1.01 MB | 332.13 kB | 331.56 kB | echarts.js -6.69 MB | 2.32 MB | 2.31 MB | 493.01 kB | 488.28 kB | antd.js +6.69 MB | 2.32 MB | 2.31 MB | 493.00 kB | 488.28 kB | antd.js -10.95 MB | 3.51 MB | 3.49 MB | 910.12 kB | 915.50 kB | typescript.js +10.95 MB | 3.51 MB | 3.49 MB | 910.09 kB | 915.50 kB | typescript.js