From b9f7db5d080e11c051c1a930b251515e361c1643 Mon Sep 17 00:00:00 2001 From: Christopher Fox Date: Fri, 1 Dec 2023 12:26:25 -0500 Subject: [PATCH] chore: ability to use sort/sortBy/sortByKey on bigint values --- src/array.test.ts | 6 ++++++ src/array.ts | 4 +++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/array.test.ts b/src/array.test.ts index 7e6779f..0acd3cd 100644 --- a/src/array.test.ts +++ b/src/array.test.ts @@ -26,6 +26,12 @@ describe("array", () => { const foos: { foo: any }[] = [{ foo: {} }, { foo: {} }]; expect(() => foos.sortByKey("foo")).toThrow("Unsupported sortBy values"); }); + + it("works for bigint fields", () => { + // Using `any` here as an easy case for the compiler not being able to catch the error + const foos: { foo: bigint }[] = [{ foo: 3n }, { foo: -1n }, { foo: 2n }]; + expect(foos.sortByKey("foo")).toEqual([{ foo: -1n }, { foo: 2n }, { foo: 3n }]); + }); }); describe("groupByObject", () => { diff --git a/src/array.ts b/src/array.ts index 8419ecd..a60578d 100644 --- a/src/array.ts +++ b/src/array.ts @@ -145,7 +145,7 @@ declare global { } } -export type Sortable = string | number | Date; +export type Sortable = string | number | Date | bigint; function isDefined(param: T | undefined | null): param is T { return param !== null && param !== undefined; @@ -177,6 +177,8 @@ Array.prototype.sortBy = function (this: Array, f: (el return !av && !bv ? 0 : !av ? 1 : -1; } else if (typeof av === "number" && typeof bv === "number") { return av - bv; + } else if (typeof av === "bigint" && typeof bv === "bigint") { + return av < bv ? -1 : av > bv ? 1 : 0; } else if (typeof av === "string" && typeof bv === "string") { return av.localeCompare(bv); } else if (av instanceof Date && bv instanceof Date) {