WeakMapConstructor.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/AbstractOperations.h>
  7. #include <LibJS/Runtime/Error.h>
  8. #include <LibJS/Runtime/GlobalObject.h>
  9. #include <LibJS/Runtime/IteratorOperations.h>
  10. #include <LibJS/Runtime/WeakMap.h>
  11. #include <LibJS/Runtime/WeakMapConstructor.h>
  12. namespace JS {
  13. WeakMapConstructor::WeakMapConstructor(Realm& realm)
  14. : NativeFunction(vm().names.WeakMap.as_string(), *realm.global_object().function_prototype())
  15. {
  16. }
  17. void WeakMapConstructor::initialize(Realm& realm)
  18. {
  19. auto& vm = this->vm();
  20. NativeFunction::initialize(realm);
  21. // 24.3.2.1 WeakMap.prototype, https://tc39.es/ecma262/#sec-weakmap.prototype
  22. define_direct_property(vm.names.prototype, realm.global_object().weak_map_prototype(), 0);
  23. define_direct_property(vm.names.length, Value(0), Attribute::Configurable);
  24. }
  25. // 24.3.1.1 WeakMap ( [ iterable ] ), https://tc39.es/ecma262/#sec-weakmap-iterable
  26. ThrowCompletionOr<Value> WeakMapConstructor::call()
  27. {
  28. auto& vm = this->vm();
  29. return vm.throw_completion<TypeError>(ErrorType::ConstructorWithoutNew, vm.names.WeakMap);
  30. }
  31. // 24.3.1.1 WeakMap ( [ iterable ] ), https://tc39.es/ecma262/#sec-weakmap-iterable
  32. ThrowCompletionOr<Object*> WeakMapConstructor::construct(FunctionObject& new_target)
  33. {
  34. auto& vm = this->vm();
  35. auto& global_object = this->global_object();
  36. auto* weak_map = TRY(ordinary_create_from_constructor<WeakMap>(global_object, new_target, &GlobalObject::weak_map_prototype));
  37. if (vm.argument(0).is_nullish())
  38. return weak_map;
  39. auto adder = TRY(weak_map->get(vm.names.set));
  40. if (!adder.is_function())
  41. return vm.throw_completion<TypeError>(ErrorType::NotAFunction, "'set' property of WeakMap");
  42. (void)TRY(get_iterator_values(vm, vm.argument(0), [&](Value iterator_value) -> Optional<Completion> {
  43. if (!iterator_value.is_object())
  44. return vm.throw_completion<TypeError>(ErrorType::NotAnObject, String::formatted("Iterator value {}", iterator_value.to_string_without_side_effects()));
  45. auto key = TRY(iterator_value.as_object().get(0));
  46. auto value = TRY(iterator_value.as_object().get(1));
  47. TRY(JS::call(global_object, adder.as_function(), weak_map, key, value));
  48. return {};
  49. }));
  50. return weak_map;
  51. }
  52. }