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+ // Split "08:00" into hours "08" and minutes "00"
7+ const [ hourString , minutes ] = time . split ( ":" ) ;
8+ let hours = Number ( hourString ) ;
9+
10+ // Determine if it is AM or PM
11+ const period = hours >= 12 ? "pm" : "am" ;
12+
13+ // Convert 24-hour format to 12-hour format
14+ if ( hours === 0 ) {
15+ hours = 12 ; // Midnight (00:xx) becomes 12:xx am
16+ } else if ( hours > 12 ) {
17+ hours = hours - 12 ; // Afternoon/evening (13:xx - 23:xx) becomes 1:xx - 11:xx pm
918 }
10- return `${ time } am` ;
11- }
1219
20+ // Pad the hours with a leading zero if needed (e.g., "8" becomes "08")
21+ const paddedHours = hours . toString ( ) . padStart ( 2 , "0" ) ;
22+
23+ return `${ paddedHours } :${ minutes } ${ period } ` ;
24+ }
25+ // Test 1: Morning time
1326const currentOutput = formatAs12HourClock ( "08:00" ) ;
1427const targetOutput = "08:00 am" ;
1528console . assert (
1629 currentOutput === targetOutput ,
1730 `current output: ${ currentOutput } , target output: ${ targetOutput } `
1831) ;
19-
32+ // Test 2: Evening time
2033const currentOutput2 = formatAs12HourClock ( "23:00" ) ;
2134const targetOutput2 = "11:00 pm" ;
2235console . assert (
@@ -57,4 +70,27 @@ const targetOutput6 = "12:00 am";
5770console . assert (
5871 currentOutput6 === targetOutput6 ,
5972 `Midnight Test Failed -> current output: ${ currentOutput6 } , target output: ${ targetOutput6 } `
73+ ) ;
74+ // Test 7: Noon edge case (12:30)
75+ const currentOutput7 = formatAs12HourClock ( "12:30" ) ;
76+ const targetOutput7 = "12:30 pm" ;
77+ console . assert (
78+ currentOutput7 === targetOutput7 ,
79+ `Noon Test Failed -> current: ${ currentOutput7 } , target: ${ targetOutput7 } `
80+ ) ;
81+
82+ // Test 8: Midnight edge case (00:30)
83+ const currentOutput8 = formatAs12HourClock ( "00:30" ) ;
84+ const targetOutput8 = "12:30 am" ;
85+ console . assert (
86+ currentOutput8 === targetOutput8 ,
87+ `Midnight Test Failed -> current: ${ currentOutput8 } , target: ${ targetOutput8 } `
88+ ) ;
89+
90+ // Test 9: Last minute of the day (23:59)
91+ const currentOutput9 = formatAs12HourClock ( "23:59" ) ;
92+ const targetOutput9 = "11:59 pm" ;
93+ console . assert (
94+ currentOutput9 === targetOutput9 ,
95+ `Late Night Test Failed -> current: ${ currentOutput9 } , target: ${ targetOutput9 } `
6096) ;
0 commit comments