From 2a43df49848267ba68a320370e3a5818bf14478e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Donny/=EA=B0=95=EB=8F=99=EC=9C=A4?= Date: Fri, 24 May 2024 09:16:42 +0900 Subject: [PATCH] fix(es/minifier): Fix comparison of `-0.0` and `0` (#8973) **Related issue:** - Closes #8972 --- .../swc_ecma_minifier/src/compress/util/mod.rs | 18 +++++++++++++++--- crates/swc_ecma_minifier/tests/exec.rs | 18 ++++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/crates/swc_ecma_minifier/src/compress/util/mod.rs b/crates/swc_ecma_minifier/src/compress/util/mod.rs index 78349213130a..eed2bbc304a0 100644 --- a/crates/swc_ecma_minifier/src/compress/util/mod.rs +++ b/crates/swc_ecma_minifier/src/compress/util/mod.rs @@ -1,4 +1,4 @@ -use std::f64; +use std::{cmp::Ordering, f64}; use swc_common::{util::take::Take, DUMMY_SP}; use swc_ecma_ast::*; @@ -486,7 +486,7 @@ pub(crate) fn eval_as_number(expr_ctx: &ExprCtx, e: &Expr) -> Option { return Some( numbers .into_iter() - .max_by(|a, b| a.partial_cmp(b).unwrap()) + .max_by(|&a, &b| cmp_num(a, b)) .unwrap_or(f64::NEG_INFINITY), ); } @@ -504,7 +504,7 @@ pub(crate) fn eval_as_number(expr_ctx: &ExprCtx, e: &Expr) -> Option { return Some( numbers .into_iter() - .min_by(|a, b| a.partial_cmp(b).unwrap()) + .min_by(|&a, &b| cmp_num(a, b)) .unwrap_or(f64::INFINITY), ); } @@ -758,3 +758,15 @@ impl Visit for SuperFinder { self.found = true; } } + +fn cmp_num(a: f64, b: f64) -> Ordering { + if a == -0.0 && b == 0.0 { + return Ordering::Greater; + } + + if a == 0.0 && b == -0.0 { + return Ordering::Less; + } + + a.partial_cmp(&b).unwrap() +} diff --git a/crates/swc_ecma_minifier/tests/exec.rs b/crates/swc_ecma_minifier/tests/exec.rs index d2cfbc610b90..8ac36c3f02e1 100644 --- a/crates/swc_ecma_minifier/tests/exec.rs +++ b/crates/swc_ecma_minifier/tests/exec.rs @@ -11293,3 +11293,21 @@ fn issue_8964() { ", ); } + +#[test] +fn issue_8982_1() { + run_default_exec_test( + " + console.log(Math.max(0, -0)); + ", + ); +} + +#[test] +fn issue_8982_2() { + run_default_exec_test( + " + console.log(Math.min(0, -0)); + ", + ); +}