Array.h 2.3 KB

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