WeakSetConstructor.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. define_property(vm.names.prototype, global_object.weak_set_prototype(), 0);
  21. define_property(vm.names.length, Value(0), Attribute::Configurable);
  22. }
  23. WeakSetConstructor::~WeakSetConstructor()
  24. {
  25. }
  26. Value WeakSetConstructor::call()
  27. {
  28. auto& vm = this->vm();
  29. vm.throw_exception<TypeError>(global_object(), ErrorType::ConstructorWithoutNew, vm.names.WeakSet);
  30. return {};
  31. }
  32. Value WeakSetConstructor::construct(Function&)
  33. {
  34. auto& vm = this->vm();
  35. if (vm.argument(0).is_nullish())
  36. return WeakSet::create(global_object());
  37. auto* weak_set = WeakSet::create(global_object());
  38. auto adder = weak_set->get(vm.names.add);
  39. if (vm.exception())
  40. return {};
  41. if (!adder.is_function()) {
  42. vm.throw_exception<TypeError>(global_object(), ErrorType::NotAFunction, "'add' property of WeakSet");
  43. return {};
  44. }
  45. get_iterator_values(global_object(), vm.argument(0), [&](Value iterator_value) {
  46. if (vm.exception())
  47. return IterationDecision::Break;
  48. (void)vm.call(adder.as_function(), Value(weak_set), iterator_value);
  49. return vm.exception() ? IterationDecision::Break : IterationDecision::Continue;
  50. });
  51. if (vm.exception())
  52. return {};
  53. return weak_set;
  54. }
  55. }