Skip to content

Commit b025250

Browse files
committed
feat: add makeDateCompareFn
1 parent ee3a184 commit b025250

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/array.test.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
toggleElement,
1313
withoutIndex,
1414
makeNumberCompareFn,
15+
makeDateCompareFn,
1516
} from './array';
1617
import { Maybe } from './types';
1718

@@ -283,6 +284,28 @@ describe('makeNumberCompareFn', () => {
283284
});
284285
});
285286

287+
describe('makeDateCompareFn', () => {
288+
it('sorts objects by date property', () => {
289+
const arr = [
290+
{ name: 'b', date: new Date('2022-01-02') },
291+
{ name: 'a', date: new Date('2022-01-01') },
292+
{ name: 'c', date: new Date('2022-01-03') },
293+
];
294+
const sorted = arr.sort(makeDateCompareFn((x) => x.date));
295+
expect(sorted.map((x) => x.name)).toEqual(['a', 'b', 'c']);
296+
});
297+
298+
it('handles null/undefined dates', () => {
299+
const arr = [
300+
{ name: 'a', date: undefined },
301+
{ name: 'b', date: new Date('2022-01-01') },
302+
{ name: 'c', date: null },
303+
];
304+
const sorted = arr.sort(makeDateCompareFn((x) => x.date));
305+
expect(sorted.map((x) => x.name)).toEqual(['a', 'c', 'b']);
306+
});
307+
});
308+
286309
describe('localeCompareStrings', () => {
287310
it('sorts strings', () => {
288311
const original: Array<string> = ['c', '', 'a', 'b'];

src/array.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,18 @@ export function makeNumberCompareFn<TSortable>(
127127
};
128128
}
129129

130+
/**
131+
* Takes a function that maps the values to sort to Dates and returns a compare function
132+
* using their timestamps, usable in `Array.toSorted` or similar APIs.
133+
*
134+
* null and undefined are coalesced to 0 and thus not distinguished and first in sort order.
135+
*/
136+
export function makeDateCompareFn<TSortable>(
137+
map: (sortable: TSortable) => Maybe<Date>,
138+
): (a: TSortable, b: TSortable) => number {
139+
return makeNumberCompareFn((sortable) => map(sortable)?.getTime());
140+
}
141+
130142
/**
131143
* Returns a compare function for values that are string, null or undefined,
132144
* using `String.prototype.localeCompare`, usable in `Array.toSorted` or similar APIs.

0 commit comments

Comments
 (0)