Array.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.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. JS_DECLARE_ALLOCATOR(Array);
  21. public:
  22. static ThrowCompletionOr<NonnullGCPtr<Array>> create(Realm&, u64 length, Object* prototype = nullptr);
  23. static NonnullGCPtr<Array> create_from(Realm&, Vector<Value> const&);
  24. // Non-standard but equivalent to CreateArrayFromList.
  25. template<typename T>
  26. static NonnullGCPtr<Array> create_from(Realm& realm, ReadonlySpan<T> elements, Function<Value(T const&)> map_fn)
  27. {
  28. auto values = MarkedVector<Value> { realm.heap() };
  29. values.ensure_capacity(elements.size());
  30. for (auto const& element : elements)
  31. values.append(map_fn(element));
  32. return Array::create_from(realm, values);
  33. }
  34. virtual ~Array() override = default;
  35. virtual ThrowCompletionOr<Optional<PropertyDescriptor>> internal_get_own_property(PropertyKey const&) const override final;
  36. virtual ThrowCompletionOr<bool> internal_define_own_property(PropertyKey const&, PropertyDescriptor const&) override final;
  37. virtual ThrowCompletionOr<bool> internal_delete(PropertyKey const&) override final;
  38. virtual ThrowCompletionOr<MarkedVector<Value>> internal_own_property_keys() const override final;
  39. [[nodiscard]] bool length_is_writable() const { return m_length_writable; }
  40. protected:
  41. explicit Array(Object& prototype);
  42. private:
  43. ThrowCompletionOr<bool> set_length(PropertyDescriptor const&);
  44. bool m_length_writable { true };
  45. };
  46. enum class Holes {
  47. SkipHoles,
  48. ReadThroughHoles,
  49. };
  50. ThrowCompletionOr<MarkedVector<Value>> sort_indexed_properties(VM&, Object const&, size_t length, Function<ThrowCompletionOr<double>(Value, Value)> const& sort_compare, Holes holes);
  51. ThrowCompletionOr<double> compare_array_elements(VM&, Value x, Value y, FunctionObject* comparefn);
  52. }