diff --git a/crates/oxc_ecmascript/src/constant_evaluation/mod.rs b/crates/oxc_ecmascript/src/constant_evaluation/mod.rs index f6570f90d75b2..9e3fc1ee7850d 100644 --- a/crates/oxc_ecmascript/src/constant_evaluation/mod.rs +++ b/crates/oxc_ecmascript/src/constant_evaluation/mod.rs @@ -145,7 +145,20 @@ pub trait ConstantEvaluation<'a>: MayHaveSideEffects { Expression::SequenceExpression(s) => { s.expressions.last().and_then(|e| self.eval_to_number(e)) } + // If the object is empty, `toString` / `valueOf` / `Symbol.toPrimitive` is not overridden. + // (assuming that those methods in Object.prototype are not modified) + // In that case, `ToPrimitive` returns `"[object Object]"` Expression::ObjectExpression(e) if e.properties.is_empty() => Some(f64::NAN), + // `ToPrimitive` for RegExp object returns `"/regexp/"` + Expression::RegExpLiteral(_) => Some(f64::NAN), + Expression::ArrayExpression(arr) => { + // If the array is empty, `ToPrimitive` returns `""` + if arr.elements.is_empty() { + Some(0.0) + } else { + None + } + } expr => { use crate::ToNumber; expr.to_number() diff --git a/crates/oxc_minifier/tests/peephole/esbuild.rs b/crates/oxc_minifier/tests/peephole/esbuild.rs index 81d581bd34ddb..5fe4a3c422e5e 100644 --- a/crates/oxc_minifier/tests/peephole/esbuild.rs +++ b/crates/oxc_minifier/tests/peephole/esbuild.rs @@ -891,9 +891,9 @@ fn constant_evaluation_test() { test("x = !5", "x = !1;"); test("x = typeof 5", "x = 'number';"); test("x = +''", "x = 0;"); - // test("x = +[]", "x = 0;"); + test("x = +[]", "x = 0;"); test("x = +{}", "x = NaN;"); - // test("x = +/1/", "x = NaN;"); + test("x = +/1/", "x = NaN;"); test("x = +[1]", "x = +[1];"); test("x = +'123'", "x = 123;"); test("x = +'-123'", "x = -123;");