Skip to content

Commit

Permalink
fix: date sorting doesn't work if one of the value is null
Browse files Browse the repository at this point in the history
  • Loading branch information
risalfajar committed Sep 19, 2023
1 parent 2559f92 commit d194bf2
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 5 deletions.
6 changes: 3 additions & 3 deletions src/lib/plugins/addSortBy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { addSortBy } from './addSortBy';
const data = readable([
{ id: 1, createdAt: new Date(2023, 1, 1), name: { first: 'Ariana', last: 'Grande' } },
{ id: 2, createdAt: new Date(1990, 1, 1), name: { first: 'Harry', last: 'Styles' } },
{ id: 3, createdAt: new Date(2025, 1, 1), name: { first: 'Doja', last: 'Cat' } },
{ id: 3, createdAt: null, name: { first: 'Doja', last: 'Cat' } },
{ id: 4, createdAt: new Date(2010, 1, 1), name: { first: 'Sam', last: 'Smith' } },
]);

Expand Down Expand Up @@ -45,7 +45,7 @@ test('ascending date sort', () => {
const vm = table.createViewModel(columns);
const rows = get(vm.rows);
const rowIds = rows.map((it) => it.isData() && it.original.id);
expect(rowIds).toStrictEqual([2, 4, 1, 3]);
expect(rowIds).toStrictEqual([3, 2, 4, 1]);
});

test('descending date sort', () => {
Expand All @@ -61,5 +61,5 @@ test('descending date sort', () => {
const vm = table.createViewModel(columns);
const rows = get(vm.rows);
const rowIds = rows.map((it) => it.isData() && it.original.id);
expect(rowIds).toStrictEqual([3, 1, 4, 2]);
expect(rowIds).toStrictEqual([1, 4, 2, 3]);
});
6 changes: 4 additions & 2 deletions src/lib/plugins/addSortBy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,10 @@ const getSortedRows = <Item, Row extends BodyRow<Item>>(
} else if (typeof valueA === 'string' || typeof valueA === 'number') {
// typeof `cellB.value` is logically equal to `cellA.value`.
order = compare(valueA, valueB as string | number);
} else if (valueA instanceof Date && valueB instanceof Date) {
order = compare(valueA.getTime(), valueB.getTime());
} else if (valueA instanceof Date || valueB instanceof Date) {
const sortValueA = valueA instanceof Date ? valueA.getTime() : 0
const sortValueB = valueB instanceof Date ? valueB.getTime() : 0
order = compare(sortValueA, sortValueB);
}
if (order !== 0) {
let orderFactor = 1;
Expand Down

0 comments on commit d194bf2

Please sign in to comment.