|
4 | 4 |
|
5 | 5 | function formatAs12HourClock(time) { |
6 | 6 | const hours = Number(time.slice(0, 2)); |
7 | | - if (hours > 12) { |
8 | | - return `${hours - 12}:00 pm`; |
| 7 | + if (hours === 0 || hours === 24) { |
| 8 | + return `12:${time.slice(3, 5)} am`; |
| 9 | + } else if (hours > 12) { |
| 10 | + return `${(hours - 12).toString().padStart(2, "0")}:${time.slice(3, 5)} pm`; |
| 11 | + } else if (hours < 12) { |
| 12 | + return `${time.slice(0, 2)}:${time.slice(3, 5)} am`; |
| 13 | + } else { |
| 14 | + return `${time.slice(0, 2)}:${time.slice(3, 5)} pm`; |
9 | 15 | } |
10 | | - return `${time} am`; |
11 | 16 | } |
12 | 17 |
|
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 | | -); |
| 18 | +// |
| 19 | +const testInputOutputPairs = [ |
| 20 | + { input: "08:00", expectedOutput: "08:00 am" }, |
| 21 | + { input: "23:00", expectedOutput: "11:00 pm" }, |
| 22 | + { input: "12:00", expectedOutput: "12:00 pm" }, |
| 23 | + { input: "13:00", expectedOutput: "01:00 pm" }, |
| 24 | + { input: "00:00", expectedOutput: "12:00 am" }, |
| 25 | + { input: "24:00", expectedOutput: "12:00 am" }, |
| 26 | + { input: "01:17", expectedOutput: "01:17 am" }, |
| 27 | + { input: "21:20", expectedOutput: "09:20 pm" }, |
| 28 | +]; |
19 | 29 |
|
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 | | -); |
| 30 | +for (const { input, expectedOutput } of testInputOutputPairs) { |
| 31 | + const currentOutput = formatAs12HourClock(input); |
| 32 | + const targetOutput = expectedOutput; |
| 33 | + console.assert( |
| 34 | + currentOutput === targetOutput, |
| 35 | + `current output: ${currentOutput}, target output: ${targetOutput}` |
| 36 | + ); |
| 37 | +} |
0 commit comments