Set.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <LibJS/Runtime/GlobalObject.h>
  8. #include <LibJS/Runtime/Map.h>
  9. #include <LibJS/Runtime/Object.h>
  10. #include <LibJS/Runtime/Value.h>
  11. namespace JS {
  12. class Set : public Object {
  13. JS_OBJECT(Set, Object);
  14. GC_DECLARE_ALLOCATOR(Set);
  15. public:
  16. static GC::Ref<Set> create(Realm&);
  17. virtual void initialize(Realm&) override;
  18. virtual ~Set() override = default;
  19. // NOTE: Unlike what the spec says, we implement Sets using an underlying map,
  20. // so all the functions below do not directly implement the operations as
  21. // defined by the specification.
  22. void set_clear() { m_values->map_clear(); }
  23. bool set_remove(Value const& value) { return m_values->map_remove(value); }
  24. bool set_has(Value const& key) const { return m_values->map_has(key); }
  25. void set_add(Value const& key) { m_values->map_set(key, js_undefined()); }
  26. size_t set_size() const { return m_values->map_size(); }
  27. auto begin() const { return const_cast<Map const&>(*m_values).begin(); }
  28. auto begin() { return m_values->begin(); }
  29. auto end() const { return m_values->end(); }
  30. GC::Ref<Set> copy() const;
  31. private:
  32. explicit Set(Object& prototype);
  33. virtual void visit_edges(Visitor& visitor) override;
  34. GC::Ptr<Map> m_values;
  35. };
  36. // 24.2.1.1 Set Records, https://tc39.es/ecma262/#sec-set-records
  37. struct SetRecord {
  38. GC::Ref<Object const> set_object; // [[SetObject]]
  39. double size { 0 }; // [[Size]
  40. GC::Ref<FunctionObject> has; // [[Has]]
  41. GC::Ref<FunctionObject> keys; // [[Keys]]
  42. };
  43. ThrowCompletionOr<SetRecord> get_set_record(VM&, Value);
  44. bool set_data_has(GC::Ref<Set>, Value);
  45. }