|
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 | + // If hours is less than 12, it should be am |
| 7 | + const [hourStr, minute] = time.split(":"); |
| 8 | + let hours = Number(hourStr); |
| 9 | + let suffix = "am"; |
| 10 | + // If hours is 0, it should be 12 am |
| 11 | + if (hours === 0) { |
| 12 | + hours = 12; |
9 | 13 | } |
10 | | - return `${time} am`; |
| 14 | + // If hours is less than 12, it should be am |
| 15 | + else if (hours === 12) { |
| 16 | + suffix = "pm"; |
| 17 | + } |
| 18 | + // If hours is greater than 12, it should be pm |
| 19 | + else if (hours > 12) { |
| 20 | + hours -= 12; |
| 21 | + suffix = "pm"; |
| 22 | + } |
| 23 | + //return `${time} am`; ignoring the actual minutes |
| 24 | + const paddedHour = String(hours).padStart(2, "0"); |
| 25 | + return `${paddedHour}:${minute} ${suffix}`; |
11 | 26 | } |
12 | 27 |
|
| 28 | +// test 1 |
13 | 29 | const currentOutput = formatAs12HourClock("08:00"); |
14 | 30 | const targetOutput = "08:00 am"; |
15 | 31 | console.assert( |
16 | 32 | currentOutput === targetOutput, |
17 | 33 | `current output: ${currentOutput}, target output: ${targetOutput}` |
18 | 34 | ); |
19 | | - |
| 35 | +// test 2 |
20 | 36 | const currentOutput2 = formatAs12HourClock("23:00"); |
21 | 37 | const targetOutput2 = "11:00 pm"; |
22 | 38 | console.assert( |
23 | 39 | currentOutput2 === targetOutput2, |
24 | 40 | `current output: ${currentOutput2}, target output: ${targetOutput2}` |
25 | 41 | ); |
| 42 | +// test3 |
| 43 | +const currentOutput3 = formatAs12HourClock("12:00"); |
| 44 | +const targetOutput3 = "12:00 pm"; |
| 45 | +console.assert( |
| 46 | + currentOutput3 === targetOutput3, |
| 47 | + `current output: ${currentOutput3}, target output: ${targetOutput3}` |
| 48 | +); |
| 49 | +//test 4 |
| 50 | +const currentOutput4 = formatAs12HourClock("14:45"); |
| 51 | +const targetOutput4 = "02:45 pm"; |
| 52 | +console.assert( |
| 53 | + currentOutput4 === targetOutput4, |
| 54 | + `current output: ${currentOutput4}, target output: ${targetOutput4}` |
| 55 | +); |
| 56 | +// test 5 |
| 57 | +const currentOutput5 = formatAs12HourClock("01:00"); |
| 58 | +const targetOutput5 = "01:00 am"; |
| 59 | +console.assert( |
| 60 | + currentOutput5 === targetOutput5, |
| 61 | + `current output: ${currentOutput5}, target output: ${targetOutput5}` |
| 62 | +); |
0 commit comments