Skip to content

Commit

Permalink
fix: optimize thread date grouping logic (#1732)
Browse files Browse the repository at this point in the history
- Use days difference for date comparison
- Add time-based sorting within groups
- Simplify date grouping implementation
- Improve performance by reducing Date objects creation"
  • Loading branch information
hexart authored Jan 17, 2025
1 parent 26fb31b commit 8b6cd38
Showing 1 changed file with 18 additions and 28 deletions.
46 changes: 18 additions & 28 deletions libs/react-client/src/utils/group.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,45 +2,35 @@ import { IThread } from 'src/types';

export const groupByDate = (data: IThread[]) => {
const groupedData: { [key: string]: IThread[] } = {};

const today = new Date();
const yesterday = new Date();
yesterday.setDate(today.getDate() - 1);
const sevenDaysAgo = new Date();
sevenDaysAgo.setDate(today.getDate() - 7);
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(today.getDate() - 30);

data.forEach((item) => {
const createdAt = new Date(item.createdAt);
const isToday = createdAt.toDateString() === today.toDateString();
const isYesterday = createdAt.toDateString() === yesterday.toDateString();
const isLast7Days = createdAt >= sevenDaysAgo;
const isLast30Days = createdAt >= thirtyDaysAgo;

today.setHours(0, 0, 0, 0);

[...data].sort((a, b) =>
new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
).forEach((item) => {
const threadDate = new Date(item.createdAt);
threadDate.setHours(0, 0, 0, 0);

const daysDiff = Math.floor((today.getTime() - threadDate.getTime()) / 86400000);

let category: string;

if (isToday) {
if (daysDiff === 0) {
category = 'Today';
} else if (isYesterday) {
} else if (daysDiff === 1) {
category = 'Yesterday';
} else if (isLast7Days) {
} else if (daysDiff <= 7) {
category = 'Previous 7 days';
} else if (isLast30Days) {
} else if (daysDiff <= 30) {
category = 'Previous 30 days';
} else {
const monthYear = createdAt.toLocaleString('default', {
category = threadDate.toLocaleString('default', {
month: 'long',
year: 'numeric'
});

category = monthYear.split(' ').slice(0, 1).join(' ');
}

if (!groupedData[category]) {
groupedData[category] = [];
}


groupedData[category] ??= [];
groupedData[category].push(item);
});

Expand Down

0 comments on commit 8b6cd38

Please sign in to comment.