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 = {
10
10
metadata : PostMetadata ,
11
11
content : string
12
12
}
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[]) {
5
5
return twMerge ( clsx ( inputs ) ) ;
6
6
}
7
7
8
- export const formatDate = ( d : Date ) : string => {
8
+ export const formatDate = ( d : string ) : string => {
9
9
return new Intl . DateTimeFormat ( 'en-US' , {
10
10
month : 'short' ,
11
11
day : '2-digit' ,
12
12
year : 'numeric'
13
- } ) . format ( d ) ;
13
+ } ) . format ( new Date ( d ) ) ;
14
14
} ;
15
15
16
- export const formatShortDate = ( d : Date ) : string => {
16
+ export const formatShortDate = ( d : string ) : string => {
17
17
return new Intl . DateTimeFormat ( 'en-US' , {
18
18
month : 'long' ,
19
19
day : '2-digit' ,
20
- } ) . format ( d ) ;
20
+ } ) . format ( new Date ( d ) ) ;
21
21
} ;
You can’t perform that action at this time.
0 commit comments