Array.h 2.2 KB

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