WeakSetConstructor.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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(GlobalObject& global_object)
  14. : NativeFunction(vm().names.WeakSet.as_string(), *global_object.function_prototype())
  15. {
  16. }
  17. void WeakSetConstructor::initialize(GlobalObject& global_object)
  18. {
  19. auto& vm = this->vm();
  20. NativeFunction::initialize(global_object);
  21. // 24.4.2.1 WeakSet.prototype, https://tc39.es/ecma262/#sec-weakset.prototype
  22. define_direct_property(vm.names.prototype, global_object.weak_set_prototype(), 0);
  23. define_direct_property(vm.names.length, Value(0), Attribute::Configurable);
  24. }
  25. WeakSetConstructor::~WeakSetConstructor()
  26. {
  27. }
  28. // 24.4.1.1 WeakSet ( [ iterable ] ), https://tc39.es/ecma262/#sec-weakset-iterable
  29. Value WeakSetConstructor::call()
  30. {
  31. auto& vm = this->vm();
  32. vm.throw_exception<TypeError>(global_object(), ErrorType::ConstructorWithoutNew, vm.names.WeakSet);
  33. return {};
  34. }
  35. // 24.4.1.1 WeakSet ( [ iterable ] ), https://tc39.es/ecma262/#sec-weakset-iterable
  36. Value WeakSetConstructor::construct(FunctionObject& new_target)
  37. {
  38. auto& vm = this->vm();
  39. auto& global_object = this->global_object();
  40. auto* weak_set = TRY_OR_DISCARD(ordinary_create_from_constructor<WeakSet>(global_object, new_target, &GlobalObject::weak_set_prototype));
  41. if (vm.exception())
  42. return {};
  43. if (vm.argument(0).is_nullish())
  44. return weak_set;
  45. auto adder = weak_set->get(vm.names.add);
  46. if (vm.exception())
  47. return {};
  48. if (!adder.is_function()) {
  49. vm.throw_exception<TypeError>(global_object, ErrorType::NotAFunction, "'add' property of WeakSet");
  50. return {};
  51. }
  52. get_iterator_values(global_object, vm.argument(0), [&](Value iterator_value) {
  53. if (vm.exception())
  54. return IterationDecision::Break;
  55. (void)vm.call(adder.as_function(), Value(weak_set), iterator_value);
  56. return vm.exception() ? IterationDecision::Break : IterationDecision::Continue;
  57. });
  58. if (vm.exception())
  59. return {};
  60. return weak_set;
  61. }
  62. }