From f5bbd5d5a9f00f6cfea994e9269a33508d65a57e Mon Sep 17 00:00:00 2001 From: sapphi-red <49056869+sapphi-red@users.noreply.github.com> Date: Mon, 3 Mar 2025 12:41:42 +0000 Subject: [PATCH] fix(ecmascript): fix toString for negative numbers (#9508) `console.log("" + -0/0)` was compressed to `console.log("-NaN")` where it should be `console.log("NaN")`. --- crates/oxc_ecmascript/src/to_string.rs | 7 +------ .../oxc_minifier/tests/ecmascript/to_string.rs | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/crates/oxc_ecmascript/src/to_string.rs b/crates/oxc_ecmascript/src/to_string.rs index 85d9d65a9fbe7..5955094e66ddf 100644 --- a/crates/oxc_ecmascript/src/to_string.rs +++ b/crates/oxc_ecmascript/src/to_string.rs @@ -90,12 +90,7 @@ impl<'a> ToJsString<'a> for NumericLiteral<'a> { fn to_js_string(&self, _is_global_reference: &impl IsGlobalReference) -> Option> { use oxc_syntax::number::ToJsString; let value = self.value; - let s = value.to_js_string(); - Some(if value == 0.0 { - Cow::Borrowed("0") - } else { - Cow::Owned(if value.is_sign_negative() && value != 0.0 { format!("-{s}") } else { s }) - }) + Some(if value == 0.0 { Cow::Borrowed("0") } else { Cow::Owned(value.to_js_string()) }) } } diff --git a/crates/oxc_minifier/tests/ecmascript/to_string.rs b/crates/oxc_minifier/tests/ecmascript/to_string.rs index fd3caee931d85..aa6fd708fb26a 100644 --- a/crates/oxc_minifier/tests/ecmascript/to_string.rs +++ b/crates/oxc_minifier/tests/ecmascript/to_string.rs @@ -54,4 +54,22 @@ fn test() { assert_eq!(empty_object_string, Some("[object Object]".into())); assert_eq!(object_with_to_string_string, None); assert_eq!(bigint_with_separators_string, Some("10".into())); + + let num_cases = [ + (0.0, "0"), + (-0.0, "0"), + (1.0, "1"), + (-1.0, "-1"), + (f64::NAN, "NaN"), + (-f64::NAN, "NaN"), + (f64::INFINITY, "Infinity"), + (f64::NEG_INFINITY, "-Infinity"), + ]; + for (num, expected) in num_cases { + let num_lit = ast.expression_numeric_literal(SPAN, num, None, NumberBase::Decimal); + assert_eq!( + num_lit.to_js_string(&WithoutGlobalReferenceInformation {}), + Some(expected.into()) + ); + } }