WeakMapConstructor.cpp 2.5 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/Error.h>
  7. #include <LibJS/Runtime/GlobalObject.h>
  8. #include <LibJS/Runtime/IteratorOperations.h>
  9. #include <LibJS/Runtime/WeakMap.h>
  10. #include <LibJS/Runtime/WeakMapConstructor.h>
  11. namespace JS {
  12. WeakMapConstructor::WeakMapConstructor(GlobalObject& global_object)
  13. : NativeFunction(vm().names.WeakMap, *global_object.function_prototype())
  14. {
  15. }
  16. void WeakMapConstructor::initialize(GlobalObject& global_object)
  17. {
  18. auto& vm = this->vm();
  19. NativeFunction::initialize(global_object);
  20. define_property(vm.names.prototype, global_object.weak_map_prototype(), 0);
  21. define_property(vm.names.length, Value(0), Attribute::Configurable);
  22. }
  23. WeakMapConstructor::~WeakMapConstructor()
  24. {
  25. }
  26. Value WeakMapConstructor::call()
  27. {
  28. auto& vm = this->vm();
  29. vm.throw_exception<TypeError>(global_object(), ErrorType::ConstructorWithoutNew, vm.names.WeakMap);
  30. return {};
  31. }
  32. // 24.3.1.1 WeakMap ( [ iterable ] ), https://tc39.es/ecma262/#sec-weakmap-iterable
  33. Value WeakMapConstructor::construct(Function&)
  34. {
  35. auto& vm = this->vm();
  36. if (vm.argument(0).is_nullish())
  37. return WeakMap::create(global_object());
  38. auto* weak_map = WeakMap::create(global_object());
  39. auto adder = weak_map->get(vm.names.set);
  40. if (vm.exception())
  41. return {};
  42. if (!adder.is_function()) {
  43. vm.throw_exception<TypeError>(global_object(), ErrorType::NotAFunction, "'set' property of WeakMap");
  44. return {};
  45. }
  46. get_iterator_values(global_object(), vm.argument(0), [&](Value iterator_value) {
  47. if (vm.exception())
  48. return IterationDecision::Break;
  49. if (!iterator_value.is_object()) {
  50. vm.throw_exception<TypeError>(global_object(), ErrorType::NotAnObject, String::formatted("Iterator value {}", iterator_value.to_string_without_side_effects()));
  51. return IterationDecision::Break;
  52. }
  53. auto key = iterator_value.as_object().get(0).value_or(js_undefined());
  54. if (vm.exception())
  55. return IterationDecision::Break;
  56. auto value = iterator_value.as_object().get(1).value_or(js_undefined());
  57. if (vm.exception())
  58. return IterationDecision::Break;
  59. (void)vm.call(adder.as_function(), Value(weak_map), key, value);
  60. return vm.exception() ? IterationDecision::Break : IterationDecision::Continue;
  61. });
  62. if (vm.exception())
  63. return {};
  64. return weak_map;
  65. }
  66. }