WeakSetConstructor.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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/WeakSet.h>
  11. #include <LibJS/Runtime/WeakSetConstructor.h>
  12. namespace JS {
  13. WeakSetConstructor::WeakSetConstructor(Realm& realm)
  14. : NativeFunction(realm.vm().names.WeakSet.as_string(), *realm.intrinsics().function_prototype())
  15. {
  16. }
  17. ThrowCompletionOr<void> WeakSetConstructor::initialize(Realm& realm)
  18. {
  19. auto& vm = this->vm();
  20. MUST_OR_THROW_OOM(NativeFunction::initialize(realm));
  21. // 24.4.2.1 WeakSet.prototype, https://tc39.es/ecma262/#sec-weakset.prototype
  22. define_direct_property(vm.names.prototype, realm.intrinsics().weak_set_prototype(), 0);
  23. define_direct_property(vm.names.length, Value(0), Attribute::Configurable);
  24. return {};
  25. }
  26. // 24.4.1.1 WeakSet ( [ iterable ] ), https://tc39.es/ecma262/#sec-weakset-iterable
  27. ThrowCompletionOr<Value> WeakSetConstructor::call()
  28. {
  29. auto& vm = this->vm();
  30. return vm.throw_completion<TypeError>(ErrorType::ConstructorWithoutNew, vm.names.WeakSet);
  31. }
  32. // 24.4.1.1 WeakSet ( [ iterable ] ), https://tc39.es/ecma262/#sec-weakset-iterable
  33. ThrowCompletionOr<NonnullGCPtr<Object>> WeakSetConstructor::construct(FunctionObject& new_target)
  34. {
  35. auto& vm = this->vm();
  36. auto weak_set = TRY(ordinary_create_from_constructor<WeakSet>(vm, new_target, &Intrinsics::weak_set_prototype));
  37. if (vm.argument(0).is_nullish())
  38. return weak_set;
  39. auto adder = TRY(weak_set->get(vm.names.add));
  40. if (!adder.is_function())
  41. return vm.throw_completion<TypeError>(ErrorType::NotAFunction, "'add' property of WeakSet");
  42. (void)TRY(get_iterator_values(vm, vm.argument(0), [&](Value iterator_value) -> Optional<Completion> {
  43. TRY(JS::call(vm, adder.as_function(), weak_set, iterator_value));
  44. return {};
  45. }));
  46. return weak_set;
  47. }
  48. }