|
3 | 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. |
4 | 4 |
|
5 | 5 | function 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 | + const period = hours >= 12 ? "pm" : "am"; |
| 10 | + |
| 11 | + hours = hours % 12; |
| 12 | + if (hours === 0) { |
| 13 | + hours = 12; |
9 | 14 | } |
10 | | - return `${time} am`; |
| 15 | + |
| 16 | + const paddedHours = hours.toString().padStart(2, "0"); |
| 17 | + |
| 18 | + return `${paddedHours}:${minutes} ${period}`; |
11 | 19 | } |
12 | 20 |
|
13 | | -const currentOutput = formatAs12HourClock("08:00"); |
14 | | -const targetOutput = "08:00 am"; |
15 | | -console.assert( |
16 | | - currentOutput === targetOutput, |
17 | | - `current output: ${currentOutput}, target output: ${targetOutput}` |
18 | | -); |
| 21 | +console.assert(formatAs12HourClock("08:00") === "08:00 am", "Morning time failed"); |
| 22 | +console.assert(formatAs12HourClock("23:00") === "11:00 pm", "Night time failed"); |
19 | 23 |
|
20 | | -const currentOutput2 = formatAs12HourClock("23:00"); |
21 | | -const targetOutput2 = "11:00 pm"; |
22 | | -console.assert( |
23 | | - currentOutput2 === targetOutput2, |
24 | | - `current output: ${currentOutput2}, target output: ${targetOutput2}` |
25 | | -); |
| 24 | +console.assert(formatAs12HourClock("00:00") === "12:00 am", "Midnight edge case failed"); |
| 25 | +console.assert(formatAs12HourClock("00:15") === "12:15 am", "Past midnight failed"); |
| 26 | + |
| 27 | +console.assert(formatAs12HourClock("12:00") === "12:00 pm", "Noon edge case failed"); |
| 28 | +console.assert(formatAs12HourClock("12:30") === "12:30 pm", "Past noon failed"); |
| 29 | + |
| 30 | +console.assert(formatAs12HourClock("13:45") === "01:45 pm", "Padding hour formatting failed"); |
0 commit comments