Array.h 1.6 KB

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