@@ -4,3 +4,36 @@ export const HOUR = 60 * MINUTE;
44export const DAY = 24 * HOUR ;
55export const WEEK = 7 * DAY ;
66export const MONTH = 30 * DAY ;
7+
8+ export const timeToString = ( ms : number ) : string => {
9+ const timeUnits = [
10+ { label : 'month' , value : MONTH } ,
11+ { label : 'week' , value : WEEK } ,
12+ { label : 'day' , value : DAY } ,
13+ { label : 'hour' , value : HOUR } ,
14+ { label : 'minute' , value : MINUTE } ,
15+ { label : 'second' , value : SECOND } ,
16+ ] ;
17+
18+ const formatTime = ( remaining : number , units : typeof timeUnits ) : string => {
19+ if ( remaining === 0 || units . length === 0 ) {
20+ return '' ;
21+ }
22+
23+ const [ currentUnit , ...restUnits ] = units ;
24+ const count = Math . floor ( remaining / currentUnit . value ) ;
25+ const remainder = remaining % currentUnit . value ;
26+
27+ if ( count === 0 ) {
28+ return formatTime ( remainder , restUnits ) ;
29+ }
30+
31+ const currentString = `${ count } ${ currentUnit . label } ${ count === 1 ? '' : 's' } ` ;
32+ const restString = formatTime ( remainder , restUnits ) ;
33+
34+ return restString ? `${ currentString } , ${ restString } ` : currentString ;
35+ } ;
36+
37+ const result = formatTime ( ms , timeUnits ) ;
38+ return result || '0 seconds' ;
39+ } ;
0 commit comments