shithub: libmujs

Download patch

ref: 85d4c8a52c9a55ae4822f99905c3d49954540e36
parent: a88e9d4c5eb94971d1948e765f16001cdc34bba6
author: Szabolcs Nagy <nsz@port70.net>
date: Thu Oct 16 17:52:09 EDT 2014

Fix Math.min and Math.max to accept zero args and handle -0

In case of no arguments +-Infinity should be returned. -0 is
smaller than +0 and any NaN input should turn the result into NaN.
(because of the NaN semantics libc fmin, fmax cannot be used: they
return the other argument if one is NaN)

--- a/jsmath.c
+++ b/jsmath.c
@@ -97,10 +97,17 @@
 static void Math_max(js_State *J)
 {
 	unsigned int i, n = js_gettop(J);
-	double x = js_tonumber(J, 1);
-	for (i = 2; i < n; ++i) {
+	double x = -INFINITY;
+	for (i = 1; i < n; ++i) {
 		double y = js_tonumber(J, i);
-		x = x > y ? x : y;
+		if (isnan(y)) {
+			x = y;
+			break;
+		}
+		if (signbit(x) == signbit(y))
+			x = x > y ? x : y;
+		else if (signbit(x))
+			x = y;
 	}
 	js_pushnumber(J, x);
 }
@@ -108,10 +115,17 @@
 static void Math_min(js_State *J)
 {
 	unsigned int i, n = js_gettop(J);
-	double x = js_tonumber(J, 1);
-	for (i = 2; i < n; ++i) {
+	double x = INFINITY;
+	for (i = 1; i < n; ++i) {
 		double y = js_tonumber(J, i);
-		x = x < y ? x : y;
+		if (isnan(y)) {
+			x = y;
+			break;
+		}
+		if (signbit(x) == signbit(y))
+			x = x < y ? x : y;
+		else if (signbit(y))
+			x = y;
 	}
 	js_pushnumber(J, x);
 }
@@ -139,8 +153,8 @@
 		jsB_propf(J, "exp", Math_exp, 1);
 		jsB_propf(J, "floor", Math_floor, 1);
 		jsB_propf(J, "log", Math_log, 1);
-		jsB_propf(J, "max", Math_max, 2);
-		jsB_propf(J, "min", Math_min, 2);
+		jsB_propf(J, "max", Math_max, 0);
+		jsB_propf(J, "min", Math_min, 0);
 		jsB_propf(J, "pow", Math_pow, 2);
 		jsB_propf(J, "random", Math_random, 0);
 		jsB_propf(J, "round", Math_round, 1);