Array.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Assertions.h>
  8. #include <AK/Function.h>
  9. #include <AK/Span.h>
  10. #include <AK/Vector.h>
  11. #include <LibJS/Runtime/Completion.h>
  12. #include <LibJS/Runtime/GlobalObject.h>
  13. #include <LibJS/Runtime/Object.h>
  14. namespace JS {
  15. class Array : public Object {
  16. JS_OBJECT(Array, Object);
  17. public:
  18. static ThrowCompletionOr<Array*> create(GlobalObject&, size_t length, Object* prototype = nullptr);
  19. static Array* create_from(GlobalObject&, Vector<Value> const&);
  20. // Non-standard but equivalent to CreateArrayFromList.
  21. template<typename T>
  22. static Array* create_from(GlobalObject& global_object, Span<T const> elements, Function<Value(T const&)> map_fn)
  23. {
  24. auto values = MarkedVector<Value> { global_object.heap() };
  25. values.ensure_capacity(elements.size());
  26. for (auto const& element : elements)
  27. values.append(map_fn(element));
  28. return Array::create_from(global_object, values);
  29. }
  30. explicit Array(Object& prototype);
  31. virtual ~Array() override;
  32. virtual ThrowCompletionOr<Optional<PropertyDescriptor>> internal_get_own_property(PropertyKey const&) const override;
  33. virtual ThrowCompletionOr<bool> internal_define_own_property(PropertyKey const&, PropertyDescriptor const&) override;
  34. virtual ThrowCompletionOr<bool> internal_delete(PropertyKey const&) override;
  35. virtual ThrowCompletionOr<MarkedVector<Value>> internal_own_property_keys() const override;
  36. [[nodiscard]] bool length_is_writable() const { return m_length_writable; };
  37. private:
  38. ThrowCompletionOr<bool> set_length(PropertyDescriptor const&);
  39. bool m_length_writable { true };
  40. };
  41. }