|
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 | 4 |
|
| 5 | + |
5 | 6 | function formatAs12HourClock(time) { |
6 | | - const hours = Number(time.slice(0, 2)); |
7 | | - if (hours > 12) { |
8 | | - return `${hours - 12}:00 pm`; |
| 7 | + const timeString = String(time); |
| 8 | + let [hours, minutes] = timeString.split(":").map(Number); |
| 9 | + if (isNaN(minutes)){ |
| 10 | + minutes = 0; |
| 11 | + } |
| 12 | + let period = "am" |
| 13 | + if (hours >= 12) { |
| 14 | + period = "pm"; |
| 15 | + if (hours > 12) { |
| 16 | + hours = hours - 12; |
| 17 | + } |
| 18 | + } else if (hours === 0) { |
| 19 | + hours = 12; |
9 | 20 | } |
10 | | - return `${time} am`; |
| 21 | + const paddedHours = String(hours).padStart(2, "0"); |
| 22 | + const paddedMinutes = String(minutes).padStart(2, "0"); |
| 23 | + return `${paddedHours}:${paddedMinutes}${period}`; |
11 | 24 | } |
12 | 25 |
|
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 | | -); |
19 | | - |
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 | | -); |
| 26 | +console.log(formatAs12HourClock("00:30")) |
| 27 | +console.log(formatAs12HourClock("23:32")) |
| 28 | +console.log(formatAs12HourClock("08:50")) |
| 29 | +console.log(formatAs12HourClock("13:00")) |
0 commit comments