diff options
author | Linus Groh <mail@linusgroh.de> | 2020-03-29 15:20:09 +0100 |
---|---|---|
committer | Andreas Kling <kling@serenityos.org> | 2020-03-29 16:45:11 +0200 |
commit | bad0556a59bc1a554b344a33529368922ae88656 (patch) | |
tree | 94c2a58b11fd3c86b6b72f27729c480b185ff3cc | |
parent | 2d3634d5f50a94e17d373912fbd15450bf7b95b1 (diff) | |
download | serenity-bad0556a59bc1a554b344a33529368922ae88656.zip |
LibJS: Handle empty strings and arrays in Value::to_number()
- An empty string is converted to 0
- An empty array is converted to 0
- An array with one item is converted to that item's numeric value
- An array with more than one item is converted to NaN
-rw-r--r-- | Libraries/LibJS/Runtime/MathObject.cpp | 14 | ||||
-rw-r--r-- | Libraries/LibJS/Runtime/Value.cpp | 12 |
2 files changed, 12 insertions, 14 deletions
diff --git a/Libraries/LibJS/Runtime/MathObject.cpp b/Libraries/LibJS/Runtime/MathObject.cpp index e596165659..8f9de1911f 100644 --- a/Libraries/LibJS/Runtime/MathObject.cpp +++ b/Libraries/LibJS/Runtime/MathObject.cpp @@ -27,7 +27,6 @@ #include <AK/FlyString.h> #include <AK/Function.h> #include <LibJS/Interpreter.h> -#include <LibJS/Runtime/Array.h> #include <LibJS/Runtime/MathObject.h> namespace JS { @@ -47,18 +46,7 @@ Value MathObject::abs(Interpreter& interpreter) if (interpreter.call_frame().arguments.is_empty()) return js_nan(); - auto argument = interpreter.call_frame().arguments[0]; - - if (argument.is_array()) { - auto& array = *static_cast<const Array*>(argument.as_object()); - if (array.length() == 0) - return Value(0); - if (array.length() > 1) - return js_nan(); - argument = array.elements()[0]; - } - - auto number = argument.to_number(); + auto number = interpreter.call_frame().arguments[0].to_number(); if (number.is_nan()) return js_nan(); return Value(number.as_double() >= 0 ? number.as_double() : -number.as_double()); diff --git a/Libraries/LibJS/Runtime/Value.cpp b/Libraries/LibJS/Runtime/Value.cpp index 240d828696..50fd735b41 100644 --- a/Libraries/LibJS/Runtime/Value.cpp +++ b/Libraries/LibJS/Runtime/Value.cpp @@ -28,6 +28,7 @@ #include <AK/String.h> #include <LibJS/Heap/Heap.h> #include <LibJS/Interpreter.h> +#include <LibJS/Runtime/Array.h> #include <LibJS/Runtime/Error.h> #include <LibJS/Runtime/Object.h> #include <LibJS/Runtime/PrimitiveString.h> @@ -128,7 +129,16 @@ Value Value::to_number() const case Type::Undefined: return js_nan(); case Type::Object: - return m_value.as_object->to_primitive(Object::PreferredType::Number).to_number(); + if (m_value.as_object->is_array()) { + auto& array = *static_cast<Array*>(m_value.as_object); + if (array.length() == 0) + return Value(0); + if (array.length() > 1) + return js_nan(); + return array.elements()[0].to_number(); + } else { + return m_value.as_object->to_primitive(Object::PreferredType::Number).to_number(); + } } ASSERT_NOT_REACHED(); |