Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions Userland/Libraries/LibJS/Runtime/TypedArray.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,79 @@ ThrowCompletionOr<TypedArrayBase*> typed_array_create(GlobalObject& global_objec
return &typed_array;
}

// 1.2.1.1 TypedArrayCreateSameType ( exemplar, argumentList ) https://tc39.es/proposal-change-array-by-copy/#typedarray-create-same-type
ThrowCompletionOr<TypedArrayBase*> typed_array_create_same_type(GlobalObject& global_object, TypedArrayBase const& exemplar, MarkedVector<Value> arguments)
{
// 1. Assert: exemplar is an Object that has [[TypedArrayName]] and [[ContentType]] internal slots.
// 2. Let constructor be the intrinsic object listed in column one of Table 63 (points to Table 72) for exemplar.[[TypedArrayName]].
auto* constructor = (global_object.*exemplar.intrinsic_constructor())();

// 3. Let result be ? TypedArrayCreate(constructor, argumentList).
auto* result = TRY(typed_array_create(global_object, *constructor, move(arguments)));

// 4. Assert: result has [[TypedArrayName]] and [[ContentType]] internal slots.
// 5. Assert: result.[[ContentType]] is exemplar.[[ContentType]].
// 6. Return result.
return result;
}

// 1.2.2.1.2 CompareTypedArrayElements ( x, y, comparefn, buffer ), https://tc39.es/proposal-change-array-by-copy/#sec-comparetypedarrayelements
ThrowCompletionOr<double> compare_typed_array_elements(GlobalObject& global_object, Value x, Value y, FunctionObject* comparefn, ArrayBuffer& buffer)
{
auto& vm = global_object.vm();
// 1. Assert: Both Type(x) and Type(y) are Number or both are BigInt.
VERIFY(((x.is_number() && y.is_number()) || (x.is_bigint() && y.is_bigint())));

// 2. If comparefn is not undefined, then
if (comparefn != nullptr) {
// a. Let v be ? ToNumber(? Call(comparefn, undefined, « x, y »)).
auto value = TRY(call(global_object, comparefn, js_undefined(), x, y));
auto value_number = TRY(value.to_number(global_object));

// b. If IsDetachedBuffer(buffer) is true, throw a TypeError exception.
if (buffer.is_detached())
return vm.throw_completion<TypeError>(global_object, ErrorType::DetachedArrayBuffer);

// c. If v is NaN, return +0𝔽.
if (value_number.is_nan())
return 0;

// d. Return v.
return value_number.as_double();
}

// 3. If x and y are both NaN, return +0𝔽.
if (x.is_nan() && y.is_nan())
return 0;

// 4. If x is NaN, return 1𝔽.
if (x.is_nan())
return 1;

// 5. If y is NaN, return -1𝔽.
if (y.is_nan())
return -1;

// 6. If x < y, return -1𝔽.
if (x.is_bigint()
? (x.as_bigint().big_integer() < y.as_bigint().big_integer())
: (x.as_double() < y.as_double()))
return -1;

// 7. If x > y, return 1𝔽.
if (x.is_bigint()
? (x.as_bigint().big_integer() > y.as_bigint().big_integer())
: (x.as_double() > y.as_double()))
return 1;

// 9. If x is +0𝔽 and y is -0𝔽, return 1𝔽.
if (x.is_positive_zero() && y.is_negative_zero())
return 1;

// 10. Return +0𝔽.
return 0;
}

void TypedArrayBase::visit_edges(Visitor& visitor)
{
Base::visit_edges(visitor);
Expand Down
2 changes: 2 additions & 0 deletions Userland/Libraries/LibJS/Runtime/TypedArray.h
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,8 @@ class TypedArray : public TypedArrayBase {
};

ThrowCompletionOr<TypedArrayBase*> typed_array_create(GlobalObject& global_object, FunctionObject& constructor, MarkedVector<Value> arguments);
ThrowCompletionOr<TypedArrayBase*> typed_array_create_same_type(GlobalObject& global_object, TypedArrayBase const& exemplar, MarkedVector<Value> arguments);
ThrowCompletionOr<double> compare_typed_array_elements(GlobalObject& global_object, Value x, Value y, FunctionObject* comparefn, ArrayBuffer&);

#define JS_DECLARE_TYPED_ARRAY(ClassName, snake_name, PrototypeName, ConstructorName, Type) \
class ClassName : public TypedArray<Type> { \
Expand Down
49 changes: 49 additions & 0 deletions Userland/Libraries/LibJS/Runtime/TypedArrayPrototype.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
*/

#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/ArrayIterator.h>
#include <LibJS/Runtime/GlobalObject.h>
#include <LibJS/Runtime/TypedArray.h>
Expand Down Expand Up @@ -56,6 +57,7 @@ void TypedArrayPrototype::initialize(GlobalObject& object)
define_native_function(vm.names.filter, filter, 1, attr);
define_native_function(vm.names.map, map, 1, attr);
define_native_function(vm.names.toLocaleString, to_locale_string, 0, attr);
define_native_function(vm.names.toSorted, to_sorted, 1, attr);

define_native_accessor(*vm.well_known_symbol_to_string_tag(), to_string_tag_getter, nullptr, Attribute::Configurable);

Expand Down Expand Up @@ -1510,4 +1512,51 @@ JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::to_locale_string)
return js_string(vm, builder.to_string());
}

// 1.2.2.1.4 %TypedArray%.prototype.toSorted ( comparefn ) https://tc39.es/proposal-change-array-by-copy/#sec-%typedarray%.prototype.toSorted
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::to_sorted)
{
auto comparefn = vm.argument(0);
// 1. If comparefn is not undefined and IsCallable(comparefn) is false, throw a TypeError exception.
if (!comparefn.is_undefined() && !comparefn.is_function())
return vm.throw_completion<TypeError>(global_object, ErrorType::NotAFunction, comparefn);

// 2. Let O be the this value.
auto* object = TRY(vm.this_value(global_object).to_object(global_object));

// 3. Perform ? ValidateTypedArray(O).
auto* typed_array = TRY(validate_typed_array_from_this(global_object));

// 4. Let buffer be obj.[[ViewedArrayBuffer]].
auto* array_buffer = typed_array->viewed_array_buffer();
VERIFY(array_buffer);

// 5. Let len be O.[[ArrayLength]].
auto length = typed_array->array_length();

// 6. Let A be ? TypedArrayCreateSameType(O, « 𝔽(len) »).
MarkedVector<Value> arguments(vm.heap());
arguments.empend(length);
auto* return_array = TRY(typed_array_create_same_type(global_object, *typed_array, move(arguments)));

// 7. NOTE: The following closure performs a numeric comparison rather than the string comparison used in Array.prototype.toSorted
// 8. Let SortCompare be a new Abstract Closure with parameters (x, y) that captures comparefn and buffer and performs the following steps when called:
Function<ThrowCompletionOr<double>(Value, Value)> sort_compare = [&](auto x, auto y) -> ThrowCompletionOr<double> {
// a. Return ? CompareTypedArrayElements(x, y, comparefn, buffer).
return TRY(compare_typed_array_elements(global_object, x, y, comparefn.is_undefined() ? nullptr : &comparefn.as_function(), *return_array->viewed_array_buffer()));
};

// 9. Let sortedList be ? SortIndexedProperties(obj, len, SortCompare, false).
auto sorted_list = TRY(sort_indexed_properties(global_object, *object, length, sort_compare, false));

// 10. Let j be 0.
// 11. Repeat, while j < len,
for (size_t j = 0; j < length; j++) {
// Perform ! Set(A, ! ToString(𝔽(j)), sortedList[j], true).
MUST(return_array->create_data_property_or_throw(j, sorted_list[j]));
// b. Set j to j + 1.
}

return return_array;
}

}
1 change: 1 addition & 0 deletions Userland/Libraries/LibJS/Runtime/TypedArrayPrototype.h
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ class TypedArrayPrototype final : public Object {
JS_DECLARE_NATIVE_FUNCTION(filter);
JS_DECLARE_NATIVE_FUNCTION(map);
JS_DECLARE_NATIVE_FUNCTION(to_locale_string);
JS_DECLARE_NATIVE_FUNCTION(to_sorted);
};

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
const TYPED_ARRAYS = [
Uint8Array,
Uint8ClampedArray,
Uint16Array,
Uint32Array,
Int8Array,
Int16Array,
Int32Array,
Float32Array,
Float64Array,
];

const BIGINT_TYPED_ARRAYS = [BigUint64Array, BigInt64Array];

test("basic functionality", () => {
TYPED_ARRAYS.forEach(T => {
expect(T.prototype.toSorted).toHaveLength(1);

const typedArray = new T([3, 1, 2]);
let sortedtypedArray = typedArray.toSorted();
expect(sortedtypedArray).not.toBe(typedArray);
expect(sortedtypedArray[0]).toBe(1);
expect(sortedtypedArray[1]).toBe(2);
expect(sortedtypedArray[2]).toBe(3);

sortedtypedArray = typedArray.toSorted(() => 0);
expect(sortedtypedArray).not.toBe(typedArray);
expect(sortedtypedArray[0]).toBe(3);
expect(sortedtypedArray[1]).toBe(1);
expect(sortedtypedArray[2]).toBe(2);
});

BIGINT_TYPED_ARRAYS.forEach(T => {
expect(T.prototype.toSorted).toHaveLength(1);

const typedArray = new T([3n, 1n, 2n]);

let sortedtypedArray = typedArray.toSorted();
expect(sortedtypedArray).not.toBe(typedArray);
expect(sortedtypedArray[0]).toBe(1n);
expect(sortedtypedArray[1]).toBe(2n);
expect(sortedtypedArray[2]).toBe(3n);

sortedtypedArray = typedArray.toSorted(() => 0);
expect(sortedtypedArray).not.toBe(typedArray);
expect(sortedtypedArray[0]).toBe(3n);
expect(sortedtypedArray[1]).toBe(1n);
expect(sortedtypedArray[2]).toBe(2n);
});
});

describe("errors", () => {
test("null or undefined this value", () => {
TYPED_ARRAYS.forEach(T => {
expect(() => {
T.prototype.toSorted.call();
}).toThrowWithMessage(TypeError, "ToObject on null or undefined");

expect(() => {
T.prototype.toSorted.call(undefined);
}).toThrowWithMessage(TypeError, "ToObject on null or undefined");

expect(() => {
T.prototype.toSorted.call(null);
}).toThrowWithMessage(TypeError, "ToObject on null or undefined");
});

BIGINT_TYPED_ARRAYS.forEach(T => {});
});

test("invalid compare function", () => {
TYPED_ARRAYS.forEach(T => {
expect(() => {
new T([]).toSorted("foo");
}).toThrowWithMessage(TypeError, "foo is not a function");
});

BIGINT_TYPED_ARRAYS.forEach(T => {
expect(() => {
new T([]).toSorted("foo");
}).toThrowWithMessage(TypeError, "foo is not a function");
});
});
});