WeakSetConstructor.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/Error.h>
  7. #include <LibJS/Runtime/GlobalObject.h>
  8. #include <LibJS/Runtime/IteratorOperations.h>
  9. #include <LibJS/Runtime/WeakSet.h>
  10. #include <LibJS/Runtime/WeakSetConstructor.h>
  11. namespace JS {
  12. WeakSetConstructor::WeakSetConstructor(GlobalObject& global_object)
  13. : NativeFunction(vm().names.WeakSet, *global_object.function_prototype())
  14. {
  15. }
  16. void WeakSetConstructor::initialize(GlobalObject& global_object)
  17. {
  18. auto& vm = this->vm();
  19. NativeFunction::initialize(global_object);
  20. // 24.4.2.1 WeakSet.prototype, https://tc39.es/ecma262/#sec-weakset.prototype
  21. define_property(vm.names.prototype, global_object.weak_set_prototype(), 0);
  22. define_property(vm.names.length, Value(0), Attribute::Configurable);
  23. }
  24. WeakSetConstructor::~WeakSetConstructor()
  25. {
  26. }
  27. // 24.4.1.1 WeakSet ( [ iterable ] ), https://tc39.es/ecma262/#sec-weakset-iterable
  28. Value WeakSetConstructor::call()
  29. {
  30. auto& vm = this->vm();
  31. vm.throw_exception<TypeError>(global_object(), ErrorType::ConstructorWithoutNew, vm.names.WeakSet);
  32. return {};
  33. }
  34. // 24.4.1.1 WeakSet ( [ iterable ] ), https://tc39.es/ecma262/#sec-weakset-iterable
  35. Value WeakSetConstructor::construct(Function&)
  36. {
  37. auto& vm = this->vm();
  38. if (vm.argument(0).is_nullish())
  39. return WeakSet::create(global_object());
  40. auto* weak_set = WeakSet::create(global_object());
  41. auto adder = weak_set->get(vm.names.add);
  42. if (vm.exception())
  43. return {};
  44. if (!adder.is_function()) {
  45. vm.throw_exception<TypeError>(global_object(), ErrorType::NotAFunction, "'add' property of WeakSet");
  46. return {};
  47. }
  48. get_iterator_values(global_object(), vm.argument(0), [&](Value iterator_value) {
  49. if (vm.exception())
  50. return IterationDecision::Break;
  51. (void)vm.call(adder.as_function(), Value(weak_set), iterator_value);
  52. return vm.exception() ? IterationDecision::Break : IterationDecision::Continue;
  53. });
  54. if (vm.exception())
  55. return {};
  56. return weak_set;
  57. }
  58. }