feat(minifier): minify call expressionsto Number (#8267)

This commit is contained in:
camc314 2025-01-06 02:21:28 +00:00
parent 092aeafdc0
commit f000596edf
2 changed files with 26 additions and 1 deletions

View file

@ -28,6 +28,10 @@ impl<'a> ToNumber<'a> for Expression<'a> {
use crate::StringToNumber;
Some(lit.value.as_str().string_to_number())
}
Expression::UnaryExpression(unary) if unary.operator.is_not() => {
let number = unary.argument.to_number()?;
Some(if number == 0.0 { 1.0 } else { 0.0 })
}
_ => None,
}
}

View file

@ -1,6 +1,6 @@
use oxc_allocator::Vec;
use oxc_ast::{ast::*, NONE};
use oxc_ecmascript::{constant_evaluation::ConstantEvaluation, ToInt32, ToJsString};
use oxc_ecmascript::{constant_evaluation::ConstantEvaluation, ToInt32, ToJsString, ToNumber};
use oxc_semantic::IsGlobalReference;
use oxc_span::{GetSpan, SPAN};
use oxc_syntax::{
@ -671,6 +671,19 @@ impl<'a, 'b> PeepholeSubstituteAlternateSyntax {
BinaryOperator::Addition,
ctx.ast.move_expression(arg),
))
} else if call_expr.callee.is_global_reference_name("Number", ctx.symbols()) {
let number = call_expr
.arguments
.get_mut(0)
.and_then(|arg| arg.as_expression_mut())?
.to_number()?;
Some(ctx.ast.expression_numeric_literal(
call_expr.span,
number,
None,
NumberBase::Decimal,
))
} else {
None
}
@ -1373,4 +1386,12 @@ mod test {
test("f(...[1,,,3])", "f(1, void 0, void 0, 3)");
test("f(a, ...[])", "f(a)");
}
#[test]
fn test_fold_number_call() {
test("Number(0)", "0");
test("Number(true)", "1");
test("Number(false)", "0");
test("Number('foo')", "NaN");
}
}