Array.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Assertions.h>
  8. #include <AK/Function.h>
  9. #include <AK/Vector.h>
  10. #include <LibJS/Runtime/Completion.h>
  11. #include <LibJS/Runtime/GlobalObject.h>
  12. #include <LibJS/Runtime/Object.h>
  13. namespace JS {
  14. class Array : public Object {
  15. JS_OBJECT(Array, Object);
  16. public:
  17. static ThrowCompletionOr<Array*> create(GlobalObject&, size_t length, Object* prototype = nullptr);
  18. static Array* create_from(GlobalObject&, Vector<Value> const&);
  19. // Non-standard but equivalent to CreateArrayFromList.
  20. template<typename T>
  21. static Array* create_from(GlobalObject& global_object, Vector<T>& elements, Function<Value(T&)> map_fn)
  22. {
  23. auto& vm = global_object.vm();
  24. auto values = MarkedValueList { global_object.heap() };
  25. values.ensure_capacity(elements.size());
  26. for (auto& element : elements) {
  27. values.append(map_fn(element));
  28. VERIFY(!vm.exception());
  29. }
  30. return Array::create_from(global_object, values);
  31. }
  32. explicit Array(Object& prototype);
  33. virtual ~Array() override;
  34. virtual ThrowCompletionOr<Optional<PropertyDescriptor>> internal_get_own_property(PropertyName const&) const override;
  35. virtual ThrowCompletionOr<bool> internal_define_own_property(PropertyName const&, PropertyDescriptor const&) override;
  36. virtual ThrowCompletionOr<bool> internal_delete(PropertyName const&) override;
  37. virtual ThrowCompletionOr<MarkedValueList> internal_own_property_keys() const override;
  38. [[nodiscard]] bool length_is_writable() const { return m_length_writable; };
  39. private:
  40. ThrowCompletionOr<bool> set_length(PropertyDescriptor const&);
  41. bool m_length_writable { true };
  42. };
  43. }