Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(minifier): minify call expressionsto Number #8267

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions crates/oxc_ecmascript/src/to_number.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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::{
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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");
}
}
Loading