|
1 | 1 | // This is the latest solution to the problem from the prep. |
2 | 2 | // Make sure to do the prep before you do the coursework |
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 | +function pad(num) { |
| 5 | + let numString = num.toString(); |
| 6 | + while (numString.length < 2) { |
| 7 | + numString = "0" + numString; |
| 8 | + } |
| 9 | + return numString; |
| 10 | +} |
4 | 11 |
|
5 | 12 | function formatAs12HourClock(time) { |
6 | 13 | const hours = Number(time.slice(0, 2)); |
7 | | - if (hours > 12) { |
8 | | - return `${hours - 12}:00 pm`; |
| 14 | + const minutes = time.slice(3, 5); |
| 15 | + if (hours === 0) { |
| 16 | + return `12:${minutes} am`; |
| 17 | + } else if (hours > 12) { |
| 18 | + return `${pad(hours - 12)}:${minutes} pm`; |
| 19 | + } else if (hours === 12) { |
| 20 | + return `12:${minutes} pm`; |
9 | 21 | } |
10 | | - return `${time} am`; |
| 22 | + return `${pad(hours)}:${minutes} am`; |
11 | 23 | } |
12 | 24 |
|
13 | | -const currentOutput = formatAs12HourClock("08:00"); |
14 | | -const targetOutput = "08:00 am"; |
| 25 | +const currentOutput = formatAs12HourClock("06:00"); |
| 26 | +const targetOutput = "06:00 am"; |
15 | 27 | console.assert( |
16 | 28 | currentOutput === targetOutput, |
17 | 29 | `current output: ${currentOutput}, target output: ${targetOutput}` |
18 | 30 | ); |
19 | 31 |
|
20 | | -const currentOutput2 = formatAs12HourClock("23:00"); |
21 | | -const targetOutput2 = "11:00 pm"; |
| 32 | +const currentOutput2 = formatAs12HourClock("12:00"); |
| 33 | +const targetOutput2 = "12:00 pm"; |
22 | 34 | console.assert( |
23 | 35 | currentOutput2 === targetOutput2, |
24 | 36 | `current output: ${currentOutput2}, target output: ${targetOutput2}` |
25 | 37 | ); |
| 38 | + |
| 39 | +const currentOutput3 = formatAs12HourClock("00:00"); |
| 40 | +const targetOutput3 = "12:00 am"; |
| 41 | +console.assert( |
| 42 | + currentOutput3 === targetOutput3, |
| 43 | + `current output: ${currentOutput3}, target output: ${targetOutput3}` |
| 44 | +); |
| 45 | + |
| 46 | +const currentOutput4 = formatAs12HourClock("22:59"); |
| 47 | +const targetOutput4 = "10:59 pm"; |
| 48 | +console.assert( |
| 49 | + currentOutput4 === targetOutput4, |
| 50 | + `current output: ${currentOutput4}, target output: ${targetOutput4}` |
| 51 | +); |
| 52 | + |
| 53 | +const currentOutput5 = formatAs12HourClock("21:30"); |
| 54 | +const targetOutput5 = "09:30 pm"; |
| 55 | +console.assert( |
| 56 | + currentOutput5 === targetOutput5, |
| 57 | + `current output: ${currentOutput5}, target output: ${targetOutput5}` |
| 58 | +); |
0 commit comments