|
4 | 4 |
|
5 | 5 | function formatAs12HourClock(time) { |
6 | 6 | const hours = Number(time.slice(0, 2)); |
| 7 | + if (hours === 0) { |
| 8 | + return `12${time.slice(2)} am`; |
| 9 | + } |
| 10 | + if (hours === 12) { |
| 11 | + return `12${time.slice(2)} pm`; |
| 12 | + } |
7 | 13 | if (hours > 12) { |
8 | | - return `${hours - 12}:00 pm`; |
| 14 | + return `${String(hours - 12).padStart(2, "0")}:${time.slice(3)} pm`; |
9 | 15 | } |
10 | 16 | return `${time} am`; |
11 | 17 | } |
12 | 18 |
|
13 | | -const currentOutput = formatAs12HourClock("08:00"); |
14 | | -const targetOutput = "08:00 am"; |
| 19 | +const currentOutput = formatAs12HourClock("08:30"); |
| 20 | +const targetOutput = "08:30 am"; |
15 | 21 | console.assert( |
16 | 22 | currentOutput === targetOutput, |
17 | | - `current output: ${currentOutput}, target output: ${targetOutput}` |
| 23 | + `current output: ${currentOutput}, target output: ${targetOutput}`, |
18 | 24 | ); |
19 | 25 |
|
20 | | -const currentOutput2 = formatAs12HourClock("23:00"); |
21 | | -const targetOutput2 = "11:00 pm"; |
| 26 | +const currentOutput2 = formatAs12HourClock("15:30"); |
| 27 | +const targetOutput2 = "03:30 pm"; |
22 | 28 | console.assert( |
23 | 29 | currentOutput2 === targetOutput2, |
24 | | - `current output: ${currentOutput2}, target output: ${targetOutput2}` |
| 30 | + `current output: ${currentOutput2}, target output: ${targetOutput2}`, |
25 | 31 | ); |
| 32 | + |
| 33 | +const currentOutput5 = formatAs12HourClock("11:59"); |
| 34 | +const targetOutput5 = "11:59 am"; |
| 35 | +console.assert( |
| 36 | + currentOutput5 === targetOutput5, |
| 37 | + `current output: ${currentOutput5}, target output: ${targetOutput5}`, |
| 38 | +); |
| 39 | + |
| 40 | +const currentOutput3 = formatAs12HourClock("00:00"); |
| 41 | +const targetOutput3 = "12:00 am"; |
| 42 | + |
| 43 | +console.assert( |
| 44 | + currentOutput3 === targetOutput3, |
| 45 | + `current output: ${currentOutput3}, target output: ${targetOutput3}`, |
| 46 | +); |
| 47 | +const currentOutput4 = formatAs12HourClock("12:02"); |
| 48 | +const targetOutput4 = "12:02 pm"; |
| 49 | + |
| 50 | +console.assert( |
| 51 | + currentOutput4 === targetOutput4, |
| 52 | + `current output: ${currentOutput4}, target output: ${targetOutput4}`, |
| 53 | +); |
| 54 | + |
| 55 | +console.log(currentOutput, targetOutput); |
| 56 | +console.log(currentOutput2, targetOutput2); |
| 57 | +console.log(currentOutput3, targetOutput3); |
| 58 | +console.log(currentOutput4, targetOutput4); |
| 59 | +console.log(currentOutput5, targetOutput5); |
0 commit comments