SetConstructor.cpp 2.5 KB

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