From 4e54d0ff21149eba820b7f12ddd3a5b0e0fecbc7 Mon Sep 17 00:00:00 2001 From: Brian Gianforcaro Date: Sat, 4 Apr 2020 23:25:23 -0700 Subject: [PATCH] LibJS: Add support for arbitrary arguments to Math.max Address the FIXME in MathObject::max to handle an arbitrary number of arguments. Also adding a test case to verify the behavior of Math.max() while I'm here. --- Libraries/LibJS/Runtime/MathObject.cpp | 21 ++++++++------------- Libraries/LibJS/Tests/Math.max.js | 14 ++++++++++++++ 2 files changed, 22 insertions(+), 13 deletions(-) create mode 100644 Libraries/LibJS/Tests/Math.max.js diff --git a/Libraries/LibJS/Runtime/MathObject.cpp b/Libraries/LibJS/Runtime/MathObject.cpp index 70aa16a4f7..fd47c7d0cf 100644 --- a/Libraries/LibJS/Runtime/MathObject.cpp +++ b/Libraries/LibJS/Runtime/MathObject.cpp @@ -115,21 +115,16 @@ Value MathObject::max(Interpreter& interpreter) if (!interpreter.argument_count()) { // FIXME: I think this should return *negative* infinity. return js_infinity(); - } - - if (interpreter.argument_count() == 1) + } else if (interpreter.argument_count() == 1) { return interpreter.argument(0).to_number(); - - if (interpreter.argument_count() == 2) { - auto a = interpreter.argument(0).to_number(); - auto b = interpreter.argument(1).to_number(); - return Value(a.as_double() > b.as_double() ? a : b); + } else { + Value max = interpreter.argument(0).to_number(); + for (size_t i = 1; i < interpreter.argument_count(); ++i) { + Value cur = interpreter.argument(i).to_number(); + max = Value(cur.as_double() > max.as_double() ? cur : max); + } + return max; } - - // FIXME: Support Math.max() with more arguments. - ASSERT_NOT_REACHED(); - return {}; } - } diff --git a/Libraries/LibJS/Tests/Math.max.js b/Libraries/LibJS/Tests/Math.max.js new file mode 100644 index 0000000000..dc4e8569eb --- /dev/null +++ b/Libraries/LibJS/Tests/Math.max.js @@ -0,0 +1,14 @@ +function assert(x) { if (!x) throw 1; } + +try { + assert(Math.max.length === 2); + assert(Math.max(1) === 1); + assert(Math.max(2, 1) === 2); + assert(Math.max(1, 2, 3) === 3); + assert(isNaN(Math.max(NaN))); + assert(isNaN(Math.max("String", 1))); + + console.log("PASS"); +} catch { + console.log("FAIL"); +}