SetConstructor.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. // 24.2.2.1 Set.prototype, https://tc39.es/ecma262/#sec-set.prototype
  21. define_property(vm.names.prototype, global_object.set_prototype(), 0);
  22. define_property(vm.names.length, Value(0), Attribute::Configurable);
  23. define_native_accessor(vm.well_known_symbol_species(), symbol_species_getter, {}, Attribute::Configurable);
  24. }
  25. SetConstructor::~SetConstructor()
  26. {
  27. }
  28. Value SetConstructor::call()
  29. {
  30. auto& vm = this->vm();
  31. vm.throw_exception<TypeError>(global_object(), ErrorType::ConstructorWithoutNew, vm.names.Set);
  32. return {};
  33. }
  34. Value SetConstructor::construct(Function&)
  35. {
  36. auto& vm = this->vm();
  37. if (vm.argument(0).is_nullish())
  38. return Set::create(global_object());
  39. auto* set = Set::create(global_object());
  40. auto adder = set->get(vm.names.add);
  41. if (vm.exception())
  42. return {};
  43. if (!adder.is_function()) {
  44. vm.throw_exception<TypeError>(global_object(), ErrorType::NotAFunction, "'add' property of Set");
  45. return {};
  46. }
  47. get_iterator_values(global_object(), vm.argument(0), [&](Value iterator_value) {
  48. if (vm.exception())
  49. return IterationDecision::Break;
  50. (void)vm.call(adder.as_function(), Value(set), iterator_value);
  51. return vm.exception() ? IterationDecision::Break : IterationDecision::Continue;
  52. });
  53. if (vm.exception())
  54. return {};
  55. return set;
  56. }
  57. JS_DEFINE_NATIVE_GETTER(SetConstructor::symbol_species_getter)
  58. {
  59. return vm.this_value(global_object);
  60. }
  61. }