LibJS: Add Value::to_size_t()

This commit is contained in:
Linus Groh 2020-04-30 22:41:30 +01:00 committed by Andreas Kling
parent 62671bea68
commit 65dbe17dd7
Notes: sideshowbarker 2024-07-19 07:08:25 +09:00
3 changed files with 13 additions and 4 deletions

View file

@ -71,10 +71,8 @@ Value FunctionPrototype::apply(Interpreter& interpreter)
return interpreter.call(function, this_arg);
if (!arg_array.is_object())
return interpreter.throw_exception<TypeError>("argument array must be an object");
size_t length = 0;
auto length_property = arg_array.as_object().get("length");
if (!length_property.is_empty())
length = length_property.to_number().to_i32();
auto length = length_property.to_size_t();
MarkedValueList arguments(interpreter.heap());
for (size_t i = 0; i < length; ++i) {
auto element = arg_array.as_object().get(String::number(i));

View file

@ -183,6 +183,16 @@ double Value::to_double() const
return to_number().as_double();
}
size_t Value::to_size_t() const
{
if (is_empty())
return 0;
auto number = to_number();
if (number.is_nan() || number.as_double() <= 0)
return 0;
return min(number.to_i32(), (i32)pow(2, 53) - 1);
}
Value greater_than(Interpreter&, Value lhs, Value rhs)
{
return Value(lhs.to_number().as_double() > rhs.to_number().as_double());
@ -313,7 +323,7 @@ Value mod(Interpreter&, Value lhs, Value rhs)
double index = lhs.to_number().as_double();
double period = rhs.to_number().as_double();
double trunc = (double)(i32) (index / period);
double trunc = (double)(i32)(index / period);
return Value(index - trunc * period);
}

View file

@ -162,6 +162,7 @@ public:
Value to_number() const;
i32 to_i32() const;
double to_double() const;
size_t to_size_t() const;
Value to_primitive(Interpreter&) const;
Object* to_object(Heap&) const;