Array.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Function.h>
  8. #include <LibJS/Runtime/Array.h>
  9. #include <LibJS/Runtime/Error.h>
  10. #include <LibJS/Runtime/GlobalObject.h>
  11. namespace JS {
  12. // 10.4.2.2 ArrayCreate, https://tc39.es/ecma262/#sec-arraycreate
  13. Array* Array::create(GlobalObject& global_object, size_t length)
  14. {
  15. if (length > NumericLimits<u32>::max()) {
  16. auto& vm = global_object.vm();
  17. vm.throw_exception<RangeError>(global_object, ErrorType::InvalidLength, "array");
  18. return nullptr;
  19. }
  20. auto* array = global_object.heap().allocate<Array>(global_object, *global_object.array_prototype());
  21. array->indexed_properties().set_array_like_size(length);
  22. return array;
  23. }
  24. // 7.3.17 CreateArrayFromList, https://tc39.es/ecma262/#sec-createarrayfromlist
  25. Array* Array::create_from(GlobalObject& global_object, const Vector<Value>& values)
  26. {
  27. auto* array = Array::create(global_object);
  28. for (size_t i = 0; i < values.size(); ++i)
  29. array->define_property(i, values[i]);
  30. return array;
  31. }
  32. Array::Array(Object& prototype)
  33. : Object(prototype)
  34. {
  35. }
  36. void Array::initialize(GlobalObject& global_object)
  37. {
  38. auto& vm = this->vm();
  39. Object::initialize(global_object);
  40. define_native_property(vm.names.length, length_getter, length_setter, Attribute::Writable);
  41. }
  42. Array::~Array()
  43. {
  44. }
  45. Array* Array::typed_this(VM& vm, GlobalObject& global_object)
  46. {
  47. auto* this_object = vm.this_value(global_object).to_object(global_object);
  48. if (!this_object)
  49. return {};
  50. if (!this_object->is_array()) {
  51. vm.throw_exception<TypeError>(global_object, ErrorType::NotAn, "Array");
  52. return nullptr;
  53. }
  54. return static_cast<Array*>(this_object);
  55. }
  56. JS_DEFINE_NATIVE_GETTER(Array::length_getter)
  57. {
  58. auto* array = typed_this(vm, global_object);
  59. if (!array)
  60. return {};
  61. return Value(array->indexed_properties().array_like_size());
  62. }
  63. JS_DEFINE_NATIVE_SETTER(Array::length_setter)
  64. {
  65. auto* array = typed_this(vm, global_object);
  66. if (!array)
  67. return;
  68. auto length = value.to_number(global_object);
  69. if (vm.exception())
  70. return;
  71. if (length.is_nan() || length.is_infinity() || length.as_double() < 0) {
  72. vm.throw_exception<RangeError>(global_object, ErrorType::InvalidLength, "array");
  73. return;
  74. }
  75. array->indexed_properties().set_array_like_size(length.as_double());
  76. }
  77. }