feat(minifier): minsize !!!foo ? bar : baz -> foo ? baz : bar (#8244)

This commit is contained in:
Boshen 2025-01-04 09:10:22 +00:00
parent 7c7f5d7af9
commit 2f52f333fa
2 changed files with 24 additions and 7 deletions

View file

@ -83,6 +83,15 @@ impl<'a> PeepholeMinimizeConditions {
if !expr.operator.is_not() {
return None;
}
if let Expression::UnaryExpression(e1) = &mut expr.argument {
if e1.operator.is_not() {
if let Expression::UnaryExpression(e2) = &mut e1.argument {
if e2.operator.is_not() {
expr.argument = ctx.ast.move_expression(&mut e2.argument);
}
}
}
}
let Expression::BinaryExpression(binary_expr) = &mut expr.argument else { return None };
let new_op = binary_expr.operator.equality_inverse_operator()?;
binary_expr.operator = new_op;
@ -345,7 +354,10 @@ impl<'a> PeepholeMinimizeConditions {
// `!a ? b() : c()` -> `a ? c() : b()`
if let Expression::UnaryExpression(test_expr) = &mut expr.test {
if test_expr.operator.is_not() {
if test_expr.operator.is_not()
// Skip `!!!a`
&& !matches!(test_expr.argument, Expression::UnaryExpression(_))
{
let test = ctx.ast.move_expression(&mut test_expr.argument);
let consequent = ctx.ast.move_expression(&mut expr.consequent);
let alternate = ctx.ast.move_expression(&mut expr.alternate);
@ -489,13 +501,12 @@ impl<'a> PeepholeMinimizeConditions {
e: &mut BinaryExpression<'a>,
ctx: &mut TraverseCtx<'a>,
) -> Option<Expression<'a>> {
// let ctx = Ctx(ctx);
if !ValueType::from(&e.left).is_boolean() {
return None;
}
let Expression::BooleanLiteral(b) = &mut e.right else {
return None;
};
if !ValueType::from(&e.left).is_boolean() {
return None;
}
match e.operator {
BinaryOperator::Inequality | BinaryOperator::StrictInequality => {
e.operator = BinaryOperator::Equality;
@ -504,7 +515,8 @@ impl<'a> PeepholeMinimizeConditions {
BinaryOperator::StrictEquality => {
e.operator = BinaryOperator::Equality;
}
_ => {}
BinaryOperator::Equality => {}
_ => return None,
}
Some(if b.value {
ctx.ast.move_expression(&mut e.left)
@ -810,6 +822,11 @@ mod test {
fold("x = !true", "x = !1");
}
#[test]
fn test_fold_triple_not() {
fold("!!!foo ? bar : baz", "foo ? baz : bar");
}
#[test]
fn test_minimize_expr_condition() {
fold("(x ? true : false) && y()", "x && y()");

View file

@ -23,5 +23,5 @@ Original | minified | minified | gzip | gzip | Fixture
6.69 MB | 2.32 MB | 2.31 MB | 492.86 kB | 488.28 kB | antd.js
10.95 MB | 3.50 MB | 3.49 MB | 909.33 kB | 915.50 kB | typescript.js
10.95 MB | 3.50 MB | 3.49 MB | 909.32 kB | 915.50 kB | typescript.js