Array.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <andreas@ladybird.org>
  3. * Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/Assertions.h>
  9. #include <AK/Concepts.h>
  10. #include <AK/Function.h>
  11. #include <AK/Span.h>
  12. #include <AK/Vector.h>
  13. #include <LibJS/Runtime/Completion.h>
  14. #include <LibJS/Runtime/GlobalObject.h>
  15. #include <LibJS/Runtime/Object.h>
  16. #include <LibJS/Runtime/VM.h>
  17. namespace JS {
  18. class Array : public Object {
  19. JS_OBJECT(Array, Object);
  20. GC_DECLARE_ALLOCATOR(Array);
  21. public:
  22. static ThrowCompletionOr<GC::Ref<Array>> create(Realm&, u64 length, Object* prototype = nullptr);
  23. static GC::Ref<Array> create_from(Realm&, ReadonlySpan<Value>);
  24. template<size_t N>
  25. static GC::Ref<Array> create_from(Realm& realm, Value const (&values)[N])
  26. {
  27. return create_from(realm, ReadonlySpan<Value> { values, N });
  28. }
  29. // Non-standard but equivalent to CreateArrayFromList.
  30. template<typename T>
  31. static GC::Ref<Array> create_from(Realm& realm, ReadonlySpan<T> elements, Function<Value(T const&)> map_fn)
  32. {
  33. auto values = GC::MarkedVector<Value> { realm.heap() };
  34. values.ensure_capacity(elements.size());
  35. for (auto const& element : elements)
  36. values.append(map_fn(element));
  37. return Array::create_from(realm, values);
  38. }
  39. virtual ~Array() override = default;
  40. virtual ThrowCompletionOr<Optional<PropertyDescriptor>> internal_get_own_property(PropertyKey const&) const override final;
  41. virtual ThrowCompletionOr<bool> internal_define_own_property(PropertyKey const&, PropertyDescriptor const&, Optional<PropertyDescriptor>* precomputed_get_own_property = nullptr) override final;
  42. virtual ThrowCompletionOr<bool> internal_delete(PropertyKey const&) override;
  43. virtual ThrowCompletionOr<GC::MarkedVector<Value>> internal_own_property_keys() const override final;
  44. [[nodiscard]] bool length_is_writable() const { return m_length_writable; }
  45. protected:
  46. explicit Array(Object& prototype);
  47. private:
  48. ThrowCompletionOr<bool> set_length(PropertyDescriptor const&);
  49. bool m_length_writable { true };
  50. };
  51. enum class Holes {
  52. SkipHoles,
  53. ReadThroughHoles,
  54. };
  55. ThrowCompletionOr<GC::MarkedVector<Value>> sort_indexed_properties(VM&, Object const&, size_t length, Function<ThrowCompletionOr<double>(Value, Value)> const& sort_compare, Holes holes);
  56. ThrowCompletionOr<double> compare_array_elements(VM&, Value x, Value y, FunctionObject* comparefn);
  57. }