1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-05-31 13:48:12 +00:00

LibJS: Implement Function.prototype.bind()

This commit is contained in:
Jack Karamanian 2020-04-19 15:03:02 -05:00 committed by Andreas Kling
parent b3800829da
commit 1fa0c7304d
10 changed files with 317 additions and 6 deletions

View file

@ -25,7 +25,9 @@
*/
#include <LibJS/Interpreter.h>
#include <LibJS/Runtime/BoundFunction.h>
#include <LibJS/Runtime/Function.h>
#include <LibJS/Runtime/GlobalObject.h>
namespace JS {
@ -41,6 +43,50 @@ Function::Function(Object& prototype, Optional<Value> bound_this, Vector<Value>
{
}
BoundFunction* Function::bind(Value bound_this_value, Vector<Value> arguments)
{
Function& target_function = is_bound_function() ? static_cast<BoundFunction&>(*this).target_function() : *this;
auto bound_this_object
= [bound_this_value, this]() -> Value {
if (bound_this().has_value()) {
return bound_this().value();
}
switch (bound_this_value.type()) {
case Value::Type::Undefined:
case Value::Type::Null:
// FIXME: Null or undefined should be passed through in strict mode.
return &interpreter().global_object();
default:
return bound_this_value.to_object(interpreter().heap());
}
}();
i32 computed_length = 0;
auto length_property = get("length");
if (interpreter().exception()) {
return nullptr;
}
if (length_property.has_value() && length_property.value().is_number()) {
computed_length = max(0, length_property.value().to_i32() - static_cast<i32>(arguments.size()));
}
Object* constructor_prototype = nullptr;
auto prototype_property = target_function.get("prototype");
if (interpreter().exception()) {
return nullptr;
}
if (prototype_property.has_value() && prototype_property.value().is_object()) {
constructor_prototype = &prototype_property.value().as_object();
}
auto all_bound_arguments = bound_arguments();
all_bound_arguments.append(move(arguments));
return interpreter().heap().allocate<BoundFunction>(target_function, bound_this_object, move(all_bound_arguments), computed_length, constructor_prototype);
}
void Function::visit_children(Visitor& visitor)
{
Object::visit_children(visitor);