|
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 | + const hours = Number(time.slice(0, 2)); |
| 7 | + const minutes = time.slice(3, 5); |
| 8 | + let ampm = "am"; |
| 9 | + let newHours = hours; |
| 10 | + |
| 11 | + if (hours === 0) { |
| 12 | + newHours = 12; // midnight |
| 13 | + } else if (hours === 12) { |
| 14 | + ampm = "pm"; // noon |
| 15 | + } else if (hours > 12) { |
| 16 | + newHours = hours - 12; |
| 17 | + ampm = "pm"; |
9 | 18 | } |
10 | | - return `${time} am`; |
11 | | -} |
12 | | - |
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 | | -); |
19 | | - |
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 | | -); |
26 | | - |
27 | | -console.log(formatAs12HourClock("23:14")) |
28 | | -console.log(formatAs12HourClock("00:00")) |
29 | | -console.log(formatAs12HourClock("00:01")) |
30 | | -console.log(formatAs12HourClock("11:59")) |
31 | | -console.log(formatAs12HourClock("12:00")) |
32 | | -console.log(formatAs12HourClock("12:01")) |
33 | | -console.log(formatAs12HourClock("13:45")) |
34 | | - |
35 | | - |
36 | | - |
37 | 19 |
|
| 20 | + const showHours = newHours.toString().padStart(2, "0"); |
| 21 | + return `${showHours}:${minutes} ${ampm}`; |
| 22 | +} |
38 | 23 |
|
| 24 | +// Now let's test different times |
39 | 25 |
|
| 26 | +console.log(formatAs12HourClock("00:00")); |
| 27 | +console.log(formatAs12HourClock("00:01")); |
| 28 | +console.log(formatAs12HourClock("08:00")); |
| 29 | +console.log(formatAs12HourClock("11:59")); |
| 30 | +console.log(formatAs12HourClock("12:00")); |
| 31 | +console.log(formatAs12HourClock("13:45")); |
| 32 | +console.log(formatAs12HourClock("23:14")); |
0 commit comments