1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-06-01 08:28:11 +00:00

LibJS: Implement Array.prototype.toSorted()

This commit is contained in:
Linus Groh 2022-06-13 07:59:19 +01:00
parent e4370b7d82
commit ce17c868c0
5 changed files with 103 additions and 0 deletions

View file

@ -348,4 +348,10 @@ describe("ability to work with generic non-array objects", () => {
expect(result).toEqual([undefined, "baz", undefined, "bar", "foo"]);
expect(result).not.toBe(o);
});
test("toSorted", () => {
const result = Array.prototype.toSorted.call(o);
expect(result).toEqual(["bar", "baz", "foo", undefined, undefined]);
expect(result).not.toBe(o);
});
});

View file

@ -0,0 +1,53 @@
describe("normal behavior", () => {
test("length is 1", () => {
expect(Array.prototype.toSorted).toHaveLength(1);
});
test("basic functionality", () => {
const a = [2, 4, 1, 3, 5];
const b = a.toSorted();
expect(a).not.toBe(b);
expect(a).toEqual([2, 4, 1, 3, 5]);
expect(b).toEqual([1, 2, 3, 4, 5]);
});
test("custom compare function", () => {
const a = [2, 4, 1, 3, 5];
const b = a.toSorted(() => 0);
expect(a).not.toBe(b);
expect(a).toEqual([2, 4, 1, 3, 5]);
expect(b).toEqual([2, 4, 1, 3, 5]);
});
test("is unscopable", () => {
expect(Array.prototype[Symbol.unscopables].toSorted).toBeTrue();
const array = [];
with (array) {
expect(() => {
toSorted;
}).toThrowWithMessage(ReferenceError, "'toSorted' is not defined");
}
});
});
describe("errors", () => {
test("null or undefined this value", () => {
expect(() => {
Array.prototype.toSorted.call();
}).toThrowWithMessage(TypeError, "ToObject on null or undefined");
expect(() => {
Array.prototype.toSorted.call(undefined);
}).toThrowWithMessage(TypeError, "ToObject on null or undefined");
expect(() => {
Array.prototype.toSorted.call(null);
}).toThrowWithMessage(TypeError, "ToObject on null or undefined");
});
test("invalid compare function", () => {
expect(() => {
[].toSorted("foo");
}).toThrowWithMessage(TypeError, "foo is not a function");
});
});