diff --git a/Userland/Libraries/LibJS/Runtime/TypedArrayPrototype.cpp b/Userland/Libraries/LibJS/Runtime/TypedArrayPrototype.cpp index b7404615c0..a895ef731e 100644 --- a/Userland/Libraries/LibJS/Runtime/TypedArrayPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/TypedArrayPrototype.cpp @@ -24,6 +24,11 @@ void TypedArrayPrototype::initialize(GlobalObject& object) // FIXME: This should be an accessor property define_native_property(vm.names.length, length_getter, nullptr, Attribute::Configurable); define_native_property(vm.names.buffer, buffer_getter, nullptr, Attribute::Configurable); +<<<<<<< HEAD +======= + define_native_property(vm.names.byteLength, byte_length_getter, nullptr, Attribute::Configurable); + define_native_property(vm.names.BYTES_PER_ELEMENT, bytes_per_element_getter, nullptr, 0); // FIXME: This should just be a normal property and not a getter. +>>>>>>> 6be44bc62... LibJS: Expose TypedArray.prototype.byteLength define_native_function(vm.names.at, at, 1, attr); } @@ -85,4 +90,16 @@ JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::buffer_getter) return Value(array_buffer); } +// https://tc39.es/ecma262/#sec-get-%typedarray%.prototype.bytelength +JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::byte_length_getter) +{ + auto typed_array = typed_array_from(vm, global_object); + if (!typed_array) + return {}; + auto* array_buffer = typed_array->viewed_array_buffer(); + VERIFY(array_buffer); + // FIXME: If array_buffer is detached, return 0. + return Value(typed_array->byte_length()); +} + } diff --git a/Userland/Libraries/LibJS/Runtime/TypedArrayPrototype.h b/Userland/Libraries/LibJS/Runtime/TypedArrayPrototype.h index 95d7989abf..270f996c89 100644 --- a/Userland/Libraries/LibJS/Runtime/TypedArrayPrototype.h +++ b/Userland/Libraries/LibJS/Runtime/TypedArrayPrototype.h @@ -21,6 +21,7 @@ public: private: JS_DECLARE_NATIVE_GETTER(length_getter); JS_DECLARE_NATIVE_GETTER(buffer_getter); + JS_DECLARE_NATIVE_GETTER(byte_length_getter); JS_DECLARE_NATIVE_FUNCTION(at); }; diff --git a/Userland/Libraries/LibJS/Tests/builtins/TypedArray/TypedArray.prototype.byteLength.js b/Userland/Libraries/LibJS/Tests/builtins/TypedArray/TypedArray.prototype.byteLength.js new file mode 100644 index 0000000000..6d647fa46b --- /dev/null +++ b/Userland/Libraries/LibJS/Tests/builtins/TypedArray/TypedArray.prototype.byteLength.js @@ -0,0 +1,19 @@ +// Update when more typed arrays get added +const TYPED_ARRAYS = [ + { array: Uint8Array, expected: 3 }, + { array: Uint16Array, expected: 6 }, + { array: Uint32Array, expected: 12 }, + { array: Int8Array, expected: 3 }, + { array: Int16Array, expected: 6 }, + { array: Int32Array, expected: 12 }, + { array: Float32Array, expected: 12 }, + { array: Float64Array, expected: 24 }, +]; + +test("basic functionality", () => { + TYPED_ARRAYS.forEach(T => { + const typedArray = new T.array([1, 2, 3]); + expect(Object.hasOwn(typedArray, "byteOffset")).toBeFalse(); + expect(typedArray.byteLength).toBe(T.expected); + }); +});