1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 14:57:35 +00:00

LibJS: Make Array.prototype.push() generic

This commit is contained in:
Linus Groh 2020-05-22 13:20:53 +01:00 committed by Andreas Kling
parent 9f7a6e116a
commit 4334a1b208
4 changed files with 42 additions and 12 deletions

View file

@ -168,12 +168,29 @@ Value ArrayPrototype::map(Interpreter& interpreter)
Value ArrayPrototype::push(Interpreter& interpreter)
{
auto* array = array_from(interpreter);
if (!array)
auto* this_object = interpreter.this_value().to_object(interpreter);
if (!this_object)
return {};
for (size_t i = 0; i < interpreter.argument_count(); ++i)
array->elements().append(interpreter.argument(i));
return Value(array->length());
if (this_object->is_array()) {
auto* array = static_cast<Array*>(this_object);
for (size_t i = 0; i < interpreter.argument_count(); ++i)
array->elements().append(interpreter.argument(i));
return Value(array->length());
}
auto length = get_length(interpreter, *this_object);
if (interpreter.exception())
return {};
auto argument_count = interpreter.argument_count();
auto new_length = length + argument_count;
if (new_length > MAX_ARRAY_LIKE_INDEX)
return interpreter.throw_exception<TypeError>("Maximum array size exceeded");
for (size_t i = 0; i < argument_count; ++i)
this_object->put_by_index(length + i, interpreter.argument(i));
auto new_length_value = Value((i32)new_length);
this_object->put("length", new_length_value);
if (interpreter.exception())
return {};
return new_length_value;
}
Value ArrayPrototype::unshift(Interpreter& interpreter)

View file

@ -43,9 +43,6 @@
#include <LibJS/Runtime/Value.h>
#include <math.h>
// 2 ** 53 - 1
#define MAX_ARRAY_LIKE_INDEX 9007199254740991.0
namespace JS {
bool Value::is_array() const
@ -261,7 +258,7 @@ i32 Value::as_i32() const
size_t Value::as_size_t() const
{
ASSERT(as_double() >= 0);
return min((double)(i32)as_double(), MAX_ARRAY_LIKE_INDEX);
return min((double)as_i32(), MAX_ARRAY_LIKE_INDEX);
}
double Value::to_double(Interpreter& interpreter) const

View file

@ -32,6 +32,9 @@
#include <LibJS/Forward.h>
#include <LibJS/Runtime/Symbol.h>
// 2 ** 53 - 1
static constexpr double MAX_ARRAY_LIKE_INDEX = 9007199254740991.0;
namespace JS {
class Value {