Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions src/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1550,8 +1550,15 @@ export static class Math {
* @param values Numeric expressions to be evaluated.
*/
public max(...values: number[]): number {
let m = Number.MIN_VALUE;
for (const v of values) if (v > m) m = v;
// -Infinity, not Number.MIN_VALUE: that is the smallest positive number, so the maximum of
// negative numbers came out as it. With no arguments the result is -Infinity, and any NaN
// makes it NaN.
let m = Number.NEGATIVE_INFINITY;
for (const v of values) {
if (isNaN(v)) return Number.NaN;
if (v > m) m = v;
}

return m;
}

Expand All @@ -1560,8 +1567,13 @@ export static class Math {
* @param values Numeric expressions to be evaluated.
*/
public min(...values: number[]): number {
let m = Number.MAX_VALUE;
for (const v of values) if (v < m) m = v;
// +Infinity, not Number.MAX_VALUE, so that Math.min() and Math.min(Infinity) are Infinity
let m = Number.POSITIVE_INFINITY;
for (const v of values) {
if (isNaN(v)) return Number.NaN;
if (v < m) m = v;
}

return m;
}

Expand Down
22 changes: 22 additions & 0 deletions tests/math_max_min.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Math.max started from Number.MIN_VALUE, the smallest positive number, so the maximum of negative
// numbers was 2.2e-308. Checked with typed comparisons rather than an `any` helper, so the test
// does not depend on how `any` values compare.

function main() {
const m = Math.max(-3, -5);
assert(m == -3, "Math.max(-3, -5)");
assert(Math.max(-1, -7) == -1, "Math.max(-1, -7)");
assert(Math.max(-2.5) == -2.5, "Math.max(-2.5)");
assert(Math.max(1, 7) == 7, "Math.max(1, 7)");
assert(Math.max() == Number.NEGATIVE_INFINITY, "Math.max()");
assert(Math.max(Number.NEGATIVE_INFINITY, -1e308) == -1e308, "Math.max(-Infinity, -1e308)");
assert(isNaN(Math.max(1, Number.NaN, 3)), "Math.max(1, NaN, 3)");

assert(Math.min(3, 5) == 3, "Math.min(3, 5)");
assert(Math.min(-1, -7) == -7, "Math.min(-1, -7)");
assert(Math.min() == Number.POSITIVE_INFINITY, "Math.min()");
assert(Math.min(Number.POSITIVE_INFINITY) == Number.POSITIVE_INFINITY, "Math.min(Infinity)");
assert(isNaN(Math.min(Number.NaN, 1)), "Math.min(NaN, 1)");

print("ALL DONE");
}