LibJS: Correctly handle mixing +0 and -0 in Math.{min,max}()

The native C++ < and > operators won't handle this correctly, so the
result was different depending on the order of arguments. This is now
fixed by explicitly checking for positive and negative zero values.

Fixes #6589.
This commit is contained in:
Linus Groh 2021-04-23 20:47:53 +02:00
parent 883e8683b2
commit 0053816e9d
Notes: sideshowbarker 2024-07-18 19:11:12 +09:00
3 changed files with 8 additions and 2 deletions

View file

@ -157,7 +157,8 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::max)
auto cur = vm.argument(i).to_number(global_object);
if (vm.exception())
return {};
max = Value(cur.as_double() > max.as_double() ? cur : max);
if ((max.is_negative_zero() && cur.is_positive_zero()) || cur.as_double() > max.as_double())
max = cur;
}
return max;
}
@ -174,7 +175,8 @@ JS_DEFINE_NATIVE_FUNCTION(MathObject::min)
auto cur = vm.argument(i).to_number(global_object);
if (vm.exception())
return {};
min = Value(cur.as_double() < min.as_double() ? cur : min);
if ((min.is_positive_zero() && cur.is_negative_zero()) || cur.as_double() < min.as_double())
min = cur;
}
return min;
}

View file

@ -5,6 +5,8 @@ test("basic functionality", () => {
expect(Math.max(1)).toBe(1);
expect(Math.max(2, 1)).toBe(2);
expect(Math.max(1, 2, 3)).toBe(3);
expect(Math.max(-0, 0)).toBe(0);
expect(Math.max(0, -0)).toBe(0);
expect(Math.max(NaN)).toBeNaN();
expect(Math.max("String", 1)).toBeNaN();
});

View file

@ -4,6 +4,8 @@ test("basic functionality", () => {
expect(Math.min(1)).toBe(1);
expect(Math.min(2, 1)).toBe(1);
expect(Math.min(1, 2, 3)).toBe(1);
expect(Math.min(-0, 0)).toBe(-0);
expect(Math.min(0, -0)).toBe(-0);
expect(Math.min(NaN)).toBeNaN();
expect(Math.min("String", 1)).toBeNaN();
});