From 18c04a471df26da8c412a6d52a10e5ea1f1d28b1 Mon Sep 17 00:00:00 2001 From: Basilisk-Dev Date: Wed, 4 Feb 2026 09:53:46 -0500 Subject: [PATCH] Issue #2551 - Initial attempt at toSorted implementation --- js/src/builtin/Array.js | 23 +++++++++++++++++++++++ js/src/jsarray.cpp | 4 +++- js/src/vm/CommonPropertyNames.h | 1 + 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/js/src/builtin/Array.js b/js/src/builtin/Array.js index 54446d2578..11a4a7485f 100644 --- a/js/src/builtin/Array.js +++ b/js/src/builtin/Array.js @@ -253,6 +253,29 @@ function ArraySort(comparefn) { return MergeSort(O, len, comparefn); } +// ES2023 22.1.3.30 Array.prototype.toSorted ( comparefn ) +function ArrayToSorted(comparefn) { + if (comparefn !== undefined) { + if (!IsCallable(comparefn)) { + ThrowTypeError(JSMSG_NOT_FUNCTION, DecompileArg(0, comparefn)); + } + } + + var O = ToObject(this); + var len = ToLength(O.length); + + var A = ArraySpeciesCreate(O, len); + for (var k = 0; k < len; k++) { + if (k in O) + _DefineDataProperty(A, k, O[k]); + else + delete A[k]; + } + + callFunction(std_Array_sort, A, comparefn); + return A; +} + /* ES5 15.4.4.18. */ function ArrayForEach(callbackfn/*, thisArg*/) { /* Step 1. */ diff --git a/js/src/jsarray.cpp b/js/src/jsarray.cpp index 6f646b3b2d..15cb23a213 100644 --- a/js/src/jsarray.cpp +++ b/js/src/jsarray.cpp @@ -3227,6 +3227,7 @@ static const JSFunctionSpec array_methods[] = { /* ES2023 proposals */ JS_SELF_HOSTED_FN("findLast", "ArrayFindLast", 1,0), JS_SELF_HOSTED_FN("findLastIndex", "ArrayFindLastIndex", 1,0), + JS_SELF_HOSTED_FN("toSorted", "ArrayToSorted", 1,0), JS_FS_END }; @@ -3401,7 +3402,8 @@ array_proto_finish(JSContext* cx, JS::HandleObject ctor, JS::HandleObject proto) !DefineProperty(cx, unscopables, cx->names().flatMap, value) || !DefineProperty(cx, unscopables, cx->names().includes, value) || !DefineProperty(cx, unscopables, cx->names().keys, value) || - !DefineProperty(cx, unscopables, cx->names().values, value)) + !DefineProperty(cx, unscopables, cx->names().values, value) || + !DefineProperty(cx, unscopables, cx->names().toSorted, value)) { return false; } diff --git a/js/src/vm/CommonPropertyNames.h b/js/src/vm/CommonPropertyNames.h index 13af5c237d..6edd49c6c0 100644 --- a/js/src/vm/CommonPropertyNames.h +++ b/js/src/vm/CommonPropertyNames.h @@ -429,6 +429,7 @@ macro(toJSON, toJSON, "toJSON") \ macro(toLocaleString, toLocaleString, "toLocaleString") \ macro(toSource, toSource, "toSource") \ + macro(toSorted, toSorted, "toSorted") \ macro(toString, toString, "toString") \ macro(toUTCString, toUTCString, "toUTCString") \ macro(true, true_, "true") \