SetConstructor.cpp 2.2 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/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(Realm& realm)
  14. : NativeFunction(realm.vm().names.Set.as_string(), *realm.intrinsics().function_prototype())
  15. {
  16. }
  17. ThrowCompletionOr<void> SetConstructor::initialize(Realm& realm)
  18. {
  19. auto& vm = this->vm();
  20. MUST_OR_THROW_OOM(NativeFunction::initialize(realm));
  21. // 24.2.2.1 Set.prototype, https://tc39.es/ecma262/#sec-set.prototype
  22. define_direct_property(vm.names.prototype, realm.intrinsics().set_prototype(), 0);
  23. define_native_accessor(realm, *vm.well_known_symbol_species(), symbol_species_getter, {}, Attribute::Configurable);
  24. define_direct_property(vm.names.length, Value(0), Attribute::Configurable);
  25. return {};
  26. }
  27. // 24.2.1.1 Set ( [ iterable ] ), https://tc39.es/ecma262/#sec-set-iterable
  28. ThrowCompletionOr<Value> SetConstructor::call()
  29. {
  30. auto& vm = this->vm();
  31. return vm.throw_completion<TypeError>(ErrorType::ConstructorWithoutNew, vm.names.Set);
  32. }
  33. // 24.2.1.1 Set ( [ iterable ] ), https://tc39.es/ecma262/#sec-set-iterable
  34. ThrowCompletionOr<NonnullGCPtr<Object>> SetConstructor::construct(FunctionObject& new_target)
  35. {
  36. auto& vm = this->vm();
  37. auto set = TRY(ordinary_create_from_constructor<Set>(vm, new_target, &Intrinsics::set_prototype));
  38. if (vm.argument(0).is_nullish())
  39. return set;
  40. auto adder = TRY(set->get(vm.names.add));
  41. if (!adder.is_function())
  42. return vm.throw_completion<TypeError>(ErrorType::NotAFunction, "'add' property of Set");
  43. (void)TRY(get_iterator_values(vm, vm.argument(0), [&](Value iterator_value) -> Optional<Completion> {
  44. TRY(JS::call(vm, adder.as_function(), set, iterator_value));
  45. return {};
  46. }));
  47. return set;
  48. }
  49. // 24.2.2.2 get Set [ @@species ], https://tc39.es/ecma262/#sec-get-set-@@species
  50. JS_DEFINE_NATIVE_FUNCTION(SetConstructor::symbol_species_getter)
  51. {
  52. return vm.this_value();
  53. }
  54. }