Array.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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/Function.h>
  10. #include <AK/Span.h>
  11. #include <AK/Vector.h>
  12. #include <LibJS/Runtime/Completion.h>
  13. #include <LibJS/Runtime/GlobalObject.h>
  14. #include <LibJS/Runtime/Object.h>
  15. namespace JS {
  16. class Array : public Object {
  17. JS_OBJECT(Array, Object);
  18. public:
  19. static ThrowCompletionOr<Array*> create(GlobalObject&, size_t length, Object* prototype = nullptr);
  20. static Array* create_from(GlobalObject&, Vector<Value> const&);
  21. // Non-standard but equivalent to CreateArrayFromList.
  22. template<typename T>
  23. static Array* create_from(GlobalObject& global_object, Span<T const> elements, Function<Value(T const&)> map_fn)
  24. {
  25. auto values = MarkedVector<Value> { global_object.heap() };
  26. values.ensure_capacity(elements.size());
  27. for (auto const& element : elements)
  28. values.append(map_fn(element));
  29. return Array::create_from(global_object, values);
  30. }
  31. explicit Array(Object& prototype);
  32. virtual ~Array() override = default;
  33. virtual ThrowCompletionOr<Optional<PropertyDescriptor>> internal_get_own_property(PropertyKey const&) const override;
  34. virtual ThrowCompletionOr<bool> internal_define_own_property(PropertyKey const&, PropertyDescriptor const&) override;
  35. virtual ThrowCompletionOr<bool> internal_delete(PropertyKey const&) override;
  36. virtual ThrowCompletionOr<MarkedVector<Value>> internal_own_property_keys() const override;
  37. [[nodiscard]] bool length_is_writable() const { return m_length_writable; };
  38. private:
  39. ThrowCompletionOr<bool> set_length(PropertyDescriptor const&);
  40. bool m_length_writable { true };
  41. };
  42. ThrowCompletionOr<double> compare_array_elements(GlobalObject&, Value x, Value y, FunctionObject* comparefn);
  43. }