MapConstructor.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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/Map.h>
  11. #include <LibJS/Runtime/MapConstructor.h>
  12. namespace JS {
  13. MapConstructor::MapConstructor(Realm& realm)
  14. : NativeFunction(realm.vm().names.Map.as_string(), *realm.intrinsics().function_prototype())
  15. {
  16. }
  17. void MapConstructor::initialize(Realm& realm)
  18. {
  19. auto& vm = this->vm();
  20. NativeFunction::initialize(realm);
  21. // 24.1.2.1 Map.prototype, https://tc39.es/ecma262/#sec-map.prototype
  22. define_direct_property(vm.names.prototype, realm.intrinsics().map_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. }
  26. // 24.1.1.1 Map ( [ iterable ] ), https://tc39.es/ecma262/#sec-map-iterable
  27. ThrowCompletionOr<Value> MapConstructor::call()
  28. {
  29. auto& vm = this->vm();
  30. return vm.throw_completion<TypeError>(ErrorType::ConstructorWithoutNew, vm.names.Map);
  31. }
  32. // 24.1.1.1 Map ( [ iterable ] ), https://tc39.es/ecma262/#sec-map-iterable
  33. ThrowCompletionOr<Object*> MapConstructor::construct(FunctionObject& new_target)
  34. {
  35. auto& vm = this->vm();
  36. auto* map = TRY(ordinary_create_from_constructor<Map>(vm, new_target, &Intrinsics::map_prototype));
  37. if (vm.argument(0).is_nullish())
  38. return map;
  39. auto adder = TRY(map->get(vm.names.set));
  40. if (!adder.is_function())
  41. return vm.throw_completion<TypeError>(ErrorType::NotAFunction, "'set' property of Map");
  42. (void)TRY(get_iterator_values(vm, vm.argument(0), [&](Value iterator_value) -> Optional<Completion> {
  43. if (!iterator_value.is_object())
  44. return vm.throw_completion<TypeError>(ErrorType::NotAnObject, String::formatted("Iterator value {}", iterator_value.to_string_without_side_effects()));
  45. auto key = TRY(iterator_value.as_object().get(0));
  46. auto value = TRY(iterator_value.as_object().get(1));
  47. TRY(JS::call(vm, adder.as_function(), map, key, value));
  48. return {};
  49. }));
  50. return map;
  51. }
  52. // 24.1.2.2 get Map [ @@species ], https://tc39.es/ecma262/#sec-get-map-@@species
  53. JS_DEFINE_NATIVE_FUNCTION(MapConstructor::symbol_species_getter)
  54. {
  55. return vm.this_value();
  56. }
  57. }