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 ) ) ;
6+ const hoursStr = time . slice ( 0 , 2 ) ;
7+ const hours = Number ( hoursStr ) ;
8+ const minutes = time . slice ( 3 , 5 ) ;
9+
10+ if ( hours === 0 ) {
11+ return `12:${ minutes } am` ;
12+ }
13+
714 if ( hours > 12 ) {
8- return `${ hours - 12 } :00 pm` ;
15+ return `${ String ( hours - 12 ) . padStart ( 2 , '0' ) } : ${ minutes } pm` ;
916 }
10- return `${ time } am` ;
17+
18+ if ( hours === 12 ) {
19+ return `12:${ minutes } pm` ;
20+ }
21+
22+ return `${ hoursStr } :${ minutes } am` ;
1123}
1224
1325const currentOutput = formatAs12HourClock ( "08:00" ) ;
@@ -23,3 +35,21 @@ console.assert(
2335 currentOutput2 === targetOutput2 ,
2436 `current output: ${ currentOutput2 } , target output: ${ targetOutput2 } `
2537) ;
38+
39+ const currentOutput3 = formatAs12HourClock ( "12:30" ) ;
40+ const targetOutput3 = "12:30 pm" ;
41+ console . assert (
42+ currentOutput3 === targetOutput3 ,
43+ `current output: ${ currentOutput3 } , target output: ${ targetOutput3 } `
44+ ) ;
45+
46+ const currentOutput4 = formatAs12HourClock ( "00:15" ) ;
47+ const targetOutput4 = "12:15 am" ;
48+ console . assert (
49+ currentOutput4 === targetOutput4 ,
50+ `current output: ${ currentOutput4 } , target output: ${ targetOutput4 } `
51+ ) ;
52+
53+ console . log ( formatAs12HourClock ( "13:15" ) ) ;
54+ console . log ( formatAs12HourClock ( "05:53" ) ) ;
55+ console . log ( formatAs12HourClock ( "19:36" ) ) ;
0 commit comments