1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 19:17:44 +00:00

LibJS: Add all of the WeakMap.prototype methods (delete, get, has, set)

This commit is contained in:
Idan Horowitz 2021-06-12 05:37:09 +03:00 committed by Linus Groh
parent 39554f3787
commit 77c2db4183
9 changed files with 182 additions and 0 deletions

View file

@ -18,6 +18,12 @@ void WeakMapPrototype::initialize(GlobalObject& global_object)
{
auto& vm = this->vm();
Object::initialize(global_object);
u8 attr = Attribute::Writable | Attribute::Configurable;
define_native_function(vm.names.delete_, delete_, 1, attr);
define_native_function(vm.names.get, get, 1, attr);
define_native_function(vm.names.has, has, 1, attr);
define_native_function(vm.names.set, set, 2, attr);
define_property(vm.well_known_symbol_to_string_tag(), js_string(global_object.heap(), vm.names.WeakMap), Attribute::Configurable);
}
@ -38,4 +44,56 @@ WeakMap* WeakMapPrototype::typed_this(VM& vm, GlobalObject& global_object)
return static_cast<WeakMap*>(this_object);
}
JS_DEFINE_NATIVE_FUNCTION(WeakMapPrototype::delete_)
{
auto* weak_map = typed_this(vm, global_object);
if (!weak_map)
return {};
auto value = vm.argument(0);
if (!value.is_object())
return Value(false);
return Value(weak_map->values().remove(&value.as_object()));
}
JS_DEFINE_NATIVE_FUNCTION(WeakMapPrototype::get)
{
auto* weak_map = typed_this(vm, global_object);
if (!weak_map)
return {};
auto value = vm.argument(0);
if (!value.is_object())
return js_undefined();
auto& values = weak_map->values();
auto result = values.find(&value.as_object());
if (result == values.end())
return js_undefined();
return result->value;
}
JS_DEFINE_NATIVE_FUNCTION(WeakMapPrototype::has)
{
auto* weak_map = typed_this(vm, global_object);
if (!weak_map)
return {};
auto value = vm.argument(0);
if (!value.is_object())
return Value(false);
auto& values = weak_map->values();
return Value(values.find(&value.as_object()) != values.end());
}
JS_DEFINE_NATIVE_FUNCTION(WeakMapPrototype::set)
{
auto* weak_map = typed_this(vm, global_object);
if (!weak_map)
return {};
auto value = vm.argument(0);
if (!value.is_object()) {
vm.throw_exception<TypeError>(global_object, ErrorType::NotAnObject, value.to_string_without_side_effects());
return {};
}
weak_map->values().set(&value.as_object(), vm.argument(1));
return weak_map;
}
}

View file

@ -20,6 +20,11 @@ public:
private:
static WeakMap* typed_this(VM&, GlobalObject&);
JS_DECLARE_NATIVE_FUNCTION(delete_);
JS_DECLARE_NATIVE_FUNCTION(get);
JS_DECLARE_NATIVE_FUNCTION(has);
JS_DECLARE_NATIVE_FUNCTION(set);
};
}