Array.cpp 2.1 KB

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