Skip to content

Truly independent web browser

LibJS: Skip indexed access when sorting a singleton

sideshowbarkera6439008da81
diff --git a/Libraries/LibJS/Rust/src/runtime/array_prototype.rs b/Libraries/LibJS/Rust/src/runtime/array_prototype.rs
index e7a9627a5c2..859a65bedde 100644
--- a/Libraries/LibJS/Rust/src/runtime/array_prototype.rs
+++ b/Libraries/LibJS/Rust/src/runtime/array_prototype.rs
@@ -1092,6 +1092,13 @@ impl ArrayPrototype {
// 3. Let len be ? LengthOfArrayLike(obj).
let length = length_of_array_like(vm, &object)?;
+ // AD-HOC: Step 8.a says "Perform ? Set(obj, ! ToString(𝔽(j)), sortedList[j], true)." All major engines skip
+ // indexed reads and writes for lengths below two. Sites rely on this when sorting frozen singletons.
+ // https://github.com/tc39/ecma262/issues/4101
+ if length < 2 {
+ return Ok(Value::from_object(object));
+ }
+
// 4. Let SortCompare be a new Abstract Closure with parameters (x, y) that captures comparefn and performs the following steps when called:
let comparefn_function = (!comparefn.is_undefined()).then(|| comparefn.as_function());
let sort_compare = |x: Value, y: Value| -> ThrowCompletionOr<f64> {
diff --git a/Tests/LibJS/Runtime/builtins/Array/Array.prototype.sort.js b/Tests/LibJS/Runtime/builtins/Array/Array.prototype.sort.js
index 5b74c7ba0ae..d871eb610a6 100644
--- a/Tests/LibJS/Runtime/builtins/Array/Array.prototype.sort.js
+++ b/Tests/LibJS/Runtime/builtins/Array/Array.prototype.sort.js
@@ -89,6 +89,36 @@ describe("Array.prototype.sort", () => {
expect(arr[2].other_property == 2);
});
+ test("sorting a frozen singleton returns the array", () => {
+ const array = Object.freeze([1]);
+ expect(array.sort()).toBe(array);
+ expect(() => array.sort(null)).toThrow(TypeError);
+ expect(() => Object.freeze([1, 2]).sort()).toThrow(TypeError);
+ });
+
+ test("sorting a singleton array-like only reads its length", () => {
+ const accesses = [];
+ const object = new Proxy(
+ { 0: 1, length: 1 },
+ {
+ get(target, property) {
+ accesses.push(property);
+ return target[property];
+ },
+ has(target, property) {
+ accesses.push(property);
+ return property in target;
+ },
+ set(target, property) {
+ accesses.push(property);
+ return false;
+ },
+ }
+ );
+ expect(Array.prototype.sort.call(object)).toBe(object);
+ expect(accesses).toEqual(["length"]);
+ });
+
test("that it makes no unnecessary calls to compare function", () => {
expectNoCallCompareFunction = function (a, b) {
expect().fail();