From d194bf2e78ecfb99e3972c2f87afadcc787b9bd1 Mon Sep 17 00:00:00 2001 From: risal Date: Tue, 19 Sep 2023 11:38:55 +0700 Subject: [PATCH] fix: date sorting doesn't work if one of the value is null --- src/lib/plugins/addSortBy.test.ts | 6 +++--- src/lib/plugins/addSortBy.ts | 6 ++++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/lib/plugins/addSortBy.test.ts b/src/lib/plugins/addSortBy.test.ts index a471462..3c81c43 100644 --- a/src/lib/plugins/addSortBy.test.ts +++ b/src/lib/plugins/addSortBy.test.ts @@ -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' } }, ]); @@ -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', () => { @@ -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]); }); diff --git a/src/lib/plugins/addSortBy.ts b/src/lib/plugins/addSortBy.ts index 5657df8..f339f83 100644 --- a/src/lib/plugins/addSortBy.ts +++ b/src/lib/plugins/addSortBy.ts @@ -138,8 +138,10 @@ const getSortedRows = >( } 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;