|
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 [hoursString, minutesString = "00"] = time.split(":"); |
| 7 | + const hours = Number(hoursString); |
| 8 | + const minutes = minutesString; |
| 9 | + |
| 10 | + let suffix = "am"; |
| 11 | + if (hours >= 12) { |
| 12 | + suffix = "pm"; |
| 13 | + } |
| 14 | + let formattedHours = hours % 12; |
| 15 | + |
| 16 | + if (formattedHours === 0) { |
| 17 | + formattedHours = 12; |
9 | 18 | } |
10 | | - return `${time} am`; |
| 19 | + return `${formattedHours}:${minutes} ${suffix}`; |
11 | 20 | } |
12 | 21 |
|
13 | 22 | const currentOutput = formatAs12HourClock("08:00"); |
14 | 23 | const targetOutput = "08:00 am"; |
15 | 24 | console.assert( |
16 | 25 | currentOutput === targetOutput, |
17 | | - `current output: ${currentOutput}, target output: ${targetOutput}` |
| 26 | + `current output: ${currentOutput}, target output: ${targetOutput}`, |
18 | 27 | ); |
19 | 28 |
|
20 | 29 | const currentOutput2 = formatAs12HourClock("23:00"); |
21 | 30 | const targetOutput2 = "11:00 pm"; |
22 | 31 | console.assert( |
23 | 32 | currentOutput2 === targetOutput2, |
24 | | - `current output: ${currentOutput2}, target output: ${targetOutput2}` |
| 33 | + `current output: ${currentOutput2}, target output: ${targetOutput2}`, |
| 34 | +); |
| 35 | +const noonOutput = formatAs12HourClock("12:00"); |
| 36 | +const noonTarget = "12:00 pm"; |
| 37 | +console.assert( |
| 38 | + noonOutput === noonTarget, |
| 39 | + `current output: ${noonOutput}, target output: ${noonTarget}`, |
| 40 | +); |
| 41 | + |
| 42 | +const midnightOutput = formatAs12HourClock("00:00"); |
| 43 | +const midnightTarget = "12:00 am"; |
| 44 | +console.assert( |
| 45 | + midnightOutput === midnightTarget, |
| 46 | + `current output: ${midnightOutput}, target output: ${midnightTarget}`, |
25 | 47 | ); |
| 48 | +console.log("All tests passed"); |
0 commit comments