File tree Expand file tree Collapse file tree 2 files changed +37
-4
lines changed Expand file tree Collapse file tree 2 files changed +37
-4
lines changed Original file line number Diff line number Diff line change @@ -10,3 +10,36 @@ export type PostData = {
1010 metadata : PostMetadata ,
1111 content : string
1212}
13+
14+ export function groupPostsByYear (
15+ posts : PostMetadata [ ]
16+ ) : { year : number ; posts : PostMetadata [ ] } [ ] {
17+ // Filter out posts with no date to avoid runtime errors
18+ // Sort posts by date in descending order
19+ // Group posts by year
20+ // Sort by year in descending order
21+
22+ posts . sort (
23+ ( a , b ) =>
24+ ( new Date ( b . date ?? "" ) . getTime ( ) || 0 ) -
25+ ( new Date ( a . date ?? "" ) . getTime ( ) || 0 ) ,
26+ )
27+
28+ const groupedByYear : { [ key : number ] : PostMetadata [ ] } = posts . reduce ( ( acc , post ) => {
29+ const year = new Date ( post . date ?? "" ) . getFullYear ( ) || 1
30+ if ( ! acc [ year ] ) {
31+ acc [ year ] = [ ] ;
32+ }
33+ acc [ year ] . push ( post ) ;
34+ return acc ;
35+ } , { } as { [ key : number ] : PostMetadata [ ] } ) ;
36+
37+ const postsByYear = Object . keys ( groupedByYear )
38+ . map ( year => ( {
39+ year : parseInt ( year ) ,
40+ posts : groupedByYear [ parseInt ( year ) ]
41+ } ) )
42+ . sort ( ( a , b ) => b . year - a . year ) ;
43+
44+ return postsByYear ;
45+ }
Original file line number Diff line number Diff line change @@ -5,17 +5,17 @@ export function cn(...inputs: ClassValue[]) {
55 return twMerge ( clsx ( inputs ) ) ;
66}
77
8- export const formatDate = ( d : Date ) : string => {
8+ export const formatDate = ( d : string ) : string => {
99 return new Intl . DateTimeFormat ( 'en-US' , {
1010 month : 'short' ,
1111 day : '2-digit' ,
1212 year : 'numeric'
13- } ) . format ( d ) ;
13+ } ) . format ( new Date ( d ) ) ;
1414} ;
1515
16- export const formatShortDate = ( d : Date ) : string => {
16+ export const formatShortDate = ( d : string ) : string => {
1717 return new Intl . DateTimeFormat ( 'en-US' , {
1818 month : 'long' ,
1919 day : '2-digit' ,
20- } ) . format ( d ) ;
20+ } ) . format ( new Date ( d ) ) ;
2121} ;
You can’t perform that action at this time.
0 commit comments