Skip to content

Commit

Permalink
chore: ability to use sort/sortBy/sortByKey on bigint values
Browse files Browse the repository at this point in the history
  • Loading branch information
chr1sjf0x committed Dec 1, 2023
1 parent 3ec0b56 commit b9f7db5
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
6 changes: 6 additions & 0 deletions src/array.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down
4 changes: 3 additions & 1 deletion src/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ declare global {
}
}

export type Sortable = string | number | Date;
export type Sortable = string | number | Date | bigint;

function isDefined<T extends any>(param: T | undefined | null): param is T {
return param !== null && param !== undefined;
Expand Down Expand Up @@ -177,6 +177,8 @@ Array.prototype.sortBy = function <T, K extends Sortable>(this: Array<T>, 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) {
Expand Down

0 comments on commit b9f7db5

Please sign in to comment.