SetConstructor.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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/Set.h>
  10. #include <LibJS/Runtime/SetConstructor.h>
  11. namespace JS {
  12. SetConstructor::SetConstructor(GlobalObject& global_object)
  13. : NativeFunction(vm().names.Set, *global_object.function_prototype())
  14. {
  15. }
  16. void SetConstructor::initialize(GlobalObject& global_object)
  17. {
  18. auto& vm = this->vm();
  19. NativeFunction::initialize(global_object);
  20. define_property(vm.names.prototype, global_object.set_prototype(), 0);
  21. define_property(vm.names.length, Value(0), Attribute::Configurable);
  22. define_native_property(vm.well_known_symbol_species(), symbol_species_getter, {}, Attribute::Configurable);
  23. }
  24. SetConstructor::~SetConstructor()
  25. {
  26. }
  27. Value SetConstructor::call()
  28. {
  29. auto& vm = this->vm();
  30. vm.throw_exception<TypeError>(global_object(), ErrorType::ConstructorWithoutNew, vm.names.Set);
  31. return {};
  32. }
  33. Value SetConstructor::construct(Function&)
  34. {
  35. auto& vm = this->vm();
  36. if (vm.argument(0).is_nullish())
  37. return Set::create(global_object());
  38. auto* set = Set::create(global_object());
  39. auto adder = set->get(vm.names.add);
  40. if (vm.exception())
  41. return {};
  42. if (!adder.is_function()) {
  43. vm.throw_exception<TypeError>(global_object(), ErrorType::NotAFunction, "'add' property of Set");
  44. return {};
  45. }
  46. get_iterator_values(global_object(), vm.argument(0), [&](Value iterator_value) {
  47. if (vm.exception())
  48. return IterationDecision::Break;
  49. (void)vm.call(adder.as_function(), Value(set), iterator_value);
  50. return vm.exception() ? IterationDecision::Break : IterationDecision::Continue;
  51. });
  52. if (vm.exception())
  53. return {};
  54. return set;
  55. }
  56. JS_DEFINE_NATIVE_GETTER(SetConstructor::symbol_species_getter)
  57. {
  58. return vm.this_value(global_object);
  59. }
  60. }