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
55function formatAs12HourClock ( time ) {
6- const hours = Number ( time . slice ( 0 , 2 ) ) ;
7- if ( hours > 12 ) {
8- return `${ hours - 12 } :00 pm` ;
6+ let hours = Number ( time . slice ( 0 , 2 ) ) ;
7+ const minutes = time . slice ( 3 , 5 ) ;
8+
9+ if ( hours === 24 ) {
10+ hours = 0 ;
911 }
10- return `${ time } am` ;
12+
13+ const period = hours < 12 ? "am" : "pm" ;
14+ hours = hours % 12 || 12 ;
15+ const paddedHours = String ( hours ) . padStart ( 2 , "0" ) ;
16+
17+ return `${ paddedHours } :${ minutes } ${ period } ` ;
1118}
1219
1320const currentOutput = formatAs12HourClock ( "08:00" ) ;
@@ -23,3 +30,31 @@ console.assert(
2330 currentOutput2 === targetOutput2 ,
2431 `current output: ${ currentOutput2 } , target output: ${ targetOutput2 } `
2532) ;
33+
34+ const currentOutput3 = formatAs12HourClock ( "00:00" ) ;
35+ const targetOutput3 = "12:00 am" ;
36+ console . assert (
37+ currentOutput3 === targetOutput3 ,
38+ `current output: ${ currentOutput3 } , target output: ${ targetOutput3 } `
39+ ) ;
40+
41+ const currentOutput4 = formatAs12HourClock ( "24:00" ) ;
42+ const targetOutput4 = "12:00 am" ;
43+ console . assert (
44+ currentOutput4 === targetOutput4 ,
45+ `current output: ${ currentOutput4 } , target output: ${ targetOutput4 } `
46+ ) ;
47+
48+ const currentOutput5 = formatAs12HourClock ( "12:00" ) ;
49+ const targetOutput5 = "12:00 pm" ;
50+ console . assert (
51+ currentOutput5 === targetOutput5 ,
52+ `current output: ${ currentOutput5 } , target output: ${ targetOutput5 } `
53+ ) ;
54+
55+ const currentOutput6 = formatAs12HourClock ( "09:41" ) ;
56+ const targetOutput6 = "09:41 am" ;
57+ console . assert (
58+ currentOutput6 === targetOutput6 ,
59+ `current output: ${ currentOutput6 } , target output: ${ targetOutput6 } `
60+ ) ;
0 commit comments