11// This is the latest solution to the problem from the prep.
22// Make sure to do the prep before you do the coursework
3- // 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.
3+ // Your task is to write tests for as many different groups of input data or edge cases as you can,
4+ // and fix any bugs you find.
45
56function formatAs12HourClock ( time ) {
67 const hours = Number ( time . slice ( 0 , 2 ) ) ;
@@ -23,3 +24,63 @@ console.assert(
2324 currentOutput2 === targetOutput2 ,
2425 `current output: ${ currentOutput2 } , target output: ${ targetOutput2 } `
2526) ;
27+
28+ const currentOutput3 = formatAs12HourClock ( "00:00" ) ;
29+ const targetOutput3 = "12:00 am" ;
30+ console . assert (
31+ currentOutput3 === targetOutput3 ,
32+ `current output: ${ currentOutput3 } , target output: ${ targetOutput3 } `
33+ ) ;
34+ const currentOutput4 = formatAs12HourClock ( "12:00" ) ;
35+ const targetOutput4 = "12:00 pm" ;
36+ console . assert (
37+ currentOutput4 === targetOutput4 ,
38+ `current output: ${ currentOutput4 } , target output: ${ targetOutput4 } `
39+ ) ;
40+
41+ const currentOutput5 = formatAs12HourClock ( "13:00" ) ;
42+ const targetOutput5 = "01:00 pm" ;
43+ console . assert (
44+ currentOutput5 === targetOutput5 ,
45+ `current output: ${ currentOutput5 } , target output: ${ targetOutput5 } `
46+
47+ ) ;
48+
49+ const currentOutput7 = formatAs12HourClock ( "25:00" ) ;
50+ const targetOutput7 = "01:00 am" ;
51+ console . assert (
52+ currentOutput7 === targetOutput7 ,
53+ `current output: ${ currentOutput7 } , target output: ${ targetOutput7 } `
54+
55+ )
56+
57+ // console.assert(formatAs12HourClock("08:00") === "08:00 am");
58+ // console.assert(formatAs12HourClock("23:00") === "11:00 pm");
59+ // console.assert(formatAs12HourClock("22:00") === "10:00 pm");
60+
61+ // Modified Code:
62+
63+ function formatAs12HourClock ( time ) {
64+ let hours = Number ( time . slice ( 0 , 2 ) ) ;
65+ const minutes = time . slice ( 3 ) ;
66+
67+ let suffix ;
68+ if ( hours >= 12 ) {
69+ suffix = "pm" ;
70+ } else {
71+ suffix = "am" ;
72+ }
73+
74+ hours = hours % 12 || 12 ; // convert 0 to 12, 13 to 1
75+ const formattedHours = hours . toString ( ) . padStart ( 2 , "0" ) ;
76+
77+ return `${ formattedHours } :${ minutes } ${ suffix } ` ;
78+
79+ }
80+
81+ const currentOutput6 = formatAs12HourClock ( "23:00" ) ;
82+ const targetOutput6 = "11:00 pm" ;
83+ console . assert (
84+ currentOutput6 === targetOutput6 ,
85+ `current output: ${ currentOutput6 } , target output: ${ targetOutput6 } `
86+ )
0 commit comments