Skip to content

Commit

Permalink
accepts different fallback values
Browse files Browse the repository at this point in the history
  • Loading branch information
spawnia committed Jun 24, 2024
1 parent 262db91 commit 7ebed43
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
28 changes: 27 additions & 1 deletion src/array.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,8 +231,9 @@ describe('makeStringCompareFn', () => {
});

describe('makeNumberCompareFn', () => {
type MaybeKeyNumber = { key?: Maybe<number> };

it('creates a compare function that sorts numbers', () => {
type MaybeKeyNumber = { key?: Maybe<number> };
const compareFn = makeNumberCompareFn<MaybeKeyNumber>(
(record) => record.key,
);
Expand All @@ -255,6 +256,31 @@ describe('makeNumberCompareFn', () => {
{ key: 3 },
]);
});

it('accepts different fallback values', () => {
const compareFn = makeNumberCompareFn<MaybeKeyNumber>(
(record) => record.key,
9001,
);
const original: Array<MaybeKeyNumber> = [
{ key: 3 },
{ key: 0 },
{ key: undefined },
{ key: 1 },
{ key: null },
{ key: 2 },
{},
];
expect(original.sort(compareFn)).toEqual([
{ key: 0 },
{ key: 1 },
{ key: 2 },
{ key: 3 },
{ key: undefined },
{ key: null },
{},
]);
});
});

describe('localeCompareStrings', () => {
Expand Down
7 changes: 4 additions & 3 deletions src/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,14 +113,15 @@ export function makeStringCompareFn<TSortable>(
* Takes a function that maps the values to sort to numbers and returns a compare function
* using subtraction, usable in `Array.toSorted` or similar APIs.
*
* null, undefined and 0 are not distinguished and first in sort order.
* null and undefined are coalesced to `fallbackValue`, by default 0, and thus not distinguished and first in sort order.
*/
export function makeNumberCompareFn<TSortable>(
map: (sortable: TSortable) => Maybe<number>,
fallbackValue: number = 0,
): (a: TSortable, b: TSortable) => number {
return (a, b) => {
const mappedA = map(a) ?? 0;
const mappedB = map(b) ?? 0;
const mappedA = map(a) ?? fallbackValue;
const mappedB = map(b) ?? fallbackValue;

return mappedA - mappedB;
};
Expand Down

0 comments on commit 7ebed43

Please sign in to comment.