22// Make sure to do the prep before you do the coursework
33// Your task is to write tests for as many different groups of input data or edge cases as you can, and fix any bugs you find.
44
5+
56function formatAs12HourClock ( time ) {
6- const hours = Number ( time . slice ( 0 , 2 ) ) ;
7- if ( hours > 12 ) {
8- return `${ hours - 12 } :00 pm` ;
7+ let [ hours , minutes ] = time . split ( ":" ) . map ( Number ) ;
8+ let period = hours >= 12 ? "pm" : "am" ;
9+
10+ if ( hours === 0 ) {
11+ hours = 12 ;
12+ } else if ( hours > 12 ) {
13+ hours -= 12 ;
914 }
10- return `${ time } am` ;
11- }
1215
16+ const hoursString = hours < 10 ? `0${ hours } ` : `${ hours } ` ;
17+ const minutesString = minutes < 10 ? `0${ minutes } ` : `${ minutes } ` ;
18+
19+ return `${ hoursString } :${ minutesString } ${ period } ` ;
1320const currentOutput = formatAs12HourClock ( "08:00" ) ;
1421const targetOutput = "08:00 am" ;
1522console . assert (
@@ -23,3 +30,17 @@ console.assert(
2330 currentOutput2 === targetOutput2 ,
2431 `current output: ${ currentOutput2 } , target output: ${ targetOutput2 } `
2532) ;
33+
34+ const currentOutput3 = formatAs12HourClock ( "21:00" ) ;
35+ const targetOutput3 = "09:00 pm" ;
36+ console . assert (
37+ currentOutput3 === targetOutput3 ,
38+ `current output: ${ currentOutput3 } , target output: ${ targetOutput3 } `
39+ ) ;
40+ }
41+
42+
43+
44+ console . log ( formatAs12HourClock ( "08:00" ) ) ; // 08:00 am
45+ console . log ( formatAs12HourClock ( "23:00" ) ) ; // 11:00 pm
46+ console . log ( formatAs12HourClock ( "21:00" ) ) ; // 09:00 pm
0 commit comments