44
55function formatAs12HourClock ( time ) {
66 const hours = Number ( time . slice ( 0 , 2 ) ) ;
7- if ( hours > 12 ) {
8- return `${ hours - 12 } :00 pm` ;
7+ const minutes = time . slice ( 3 , 5 ) ;
8+ if ( hours >= 12 ) {
9+ return `${ hours - 12 } :${ minutes } pm` ;
910 }
1011 return `${ time } am` ;
1112}
@@ -23,3 +24,75 @@ console.assert(
2324 currentOutput2 === targetOutput2 ,
2425 `current output: ${ currentOutput2 } , target output: ${ targetOutput2 } `
2526) ;
27+
28+ // Midnight
29+ const outMidnight = formatAs12HourClock ( "00:00" ) ;
30+ const targetMidnight = "00:00 am" ;
31+ console . assert (
32+ outMidnight === targetMidnight ,
33+ `current output: ${ outMidnight } , target output: ${ targetMidnight } `
34+ ) ;
35+
36+ // Noon
37+ const outNoon = formatAs12HourClock ( "12:00" ) ;
38+ const targetNoon = "12:00 pm" ;
39+ console . assert (
40+ outNoon === targetNoon ,
41+ `current output: ${ outNoon } , target output: ${ targetNoon } `
42+ ) ;
43+
44+ // 1 PM
45+ const out13 = formatAs12HourClock ( "13:00" ) ;
46+ const target13 = "1:00 pm" ;
47+ console . assert (
48+ out13 === target13 ,
49+ `current output: ${ out13 } , target output: ${ target13 } `
50+ ) ;
51+
52+ // 12:59 PM
53+ const out1259 = formatAs12HourClock ( "12:59" ) ;
54+ const target1259 = "12:59 pm" ;
55+ console . assert (
56+ out1259 === target1259 ,
57+ `current output: ${ out1259 } , target output: ${ target1259 } `
58+ ) ;
59+
60+ // 11:59 PM
61+ const out2359 = formatAs12HourClock ( "23:59" ) ;
62+ const target2359 = "11:59 pm" ;
63+ console . assert (
64+ out2359 === target2359 ,
65+ `current output: ${ out2359 } , target output: ${ target2359 } `
66+ ) ;
67+
68+ // 01:00 AM
69+ const out1 = formatAs12HourClock ( "01:00" ) ;
70+ const target1 = "01:00 am" ;
71+ console . assert (
72+ out1 === target1 ,
73+ `current output: ${ out1 } , target output: ${ target1 } `
74+ ) ;
75+
76+ // 10:30 AM
77+ const out1030 = formatAs12HourClock ( "10:30" ) ;
78+ const target1030 = "10:30 am" ;
79+ console . assert (
80+ out1030 === target1030 ,
81+ `current output: ${ out1030 } , target output: ${ target1030 } `
82+ ) ;
83+
84+ // 15:45 PM
85+ const out1545 = formatAs12HourClock ( "15:45" ) ;
86+ const target1545 = "3:45 pm" ;
87+ console . assert (
88+ out1545 === target1545 ,
89+ `current output: ${ out1545 } , target output: ${ target1545 } `
90+ ) ;
91+
92+ // Edge: single digit hour
93+ const outSingle = formatAs12HourClock ( "7:00" ) ;
94+ const targetSingle = "7:00 am" ;
95+ console . assert (
96+ outSingle === targetSingle ,
97+ `current output: ${ outSingle } , target output: ${ targetSingle } `
98+ ) ;
0 commit comments