Map.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/Map.h>
  7. namespace JS {
  8. Map* Map::create(GlobalObject& global_object)
  9. {
  10. return global_object.heap().allocate<Map>(global_object, *global_object.map_prototype());
  11. }
  12. Map::Map(Object& prototype)
  13. : Object(prototype)
  14. {
  15. }
  16. Map::~Map()
  17. {
  18. }
  19. // 24.1.3.1 Map.prototype.clear ( ), https://tc39.es/ecma262/#sec-map.prototype.clear
  20. void Map::map_clear()
  21. {
  22. m_keys.clear();
  23. m_entries.clear();
  24. }
  25. // 24.1.3.3 Map.prototype.delete ( key ), https://tc39.es/ecma262/#sec-map.prototype.delete
  26. bool Map::map_remove(Value const& key)
  27. {
  28. Optional<size_t> index;
  29. for (auto it = m_keys.begin(); !it.is_end(); ++it) {
  30. if (ValueTraits::equals(*it, key)) {
  31. index = it.key();
  32. break;
  33. }
  34. }
  35. if (!index.has_value())
  36. return false;
  37. m_keys.remove(*index);
  38. m_entries.remove(key);
  39. return true;
  40. }
  41. // 24.1.3.6 Map.prototype.get ( key ), https://tc39.es/ecma262/#sec-map.prototype.get
  42. Optional<Value> Map::map_get(Value const& key) const
  43. {
  44. if (auto it = m_entries.find(key); it != m_entries.end())
  45. return it->value;
  46. return {};
  47. }
  48. // 24.1.3.7 Map.prototype.has ( key ), https://tc39.es/ecma262/#sec-map.prototype.has
  49. bool Map::map_has(Value const& key) const
  50. {
  51. return m_entries.contains(key);
  52. }
  53. // 24.1.3.9 Map.prototype.set ( key, value ), https://tc39.es/ecma262/#sec-map.prototype.set
  54. void Map::map_set(Value const& key, Value value)
  55. {
  56. auto it = m_entries.find(key);
  57. if (it != m_entries.end()) {
  58. it->value = value;
  59. } else {
  60. auto index = m_next_insertion_id++;
  61. m_keys.insert(index, key);
  62. m_entries.set(key, value);
  63. }
  64. }
  65. size_t Map::map_size() const
  66. {
  67. return m_keys.size();
  68. }
  69. void Map::visit_edges(Cell::Visitor& visitor)
  70. {
  71. Base::visit_edges(visitor);
  72. for (auto& value : m_entries) {
  73. visitor.visit(value.key);
  74. visitor.visit(value.value);
  75. }
  76. }
  77. }