|
1 | 1 | function formatAs12HourClock(time) { |
2 | | - const hours = Number(time.slice(0, 2)); |
| 2 | + const slicedHours = time.slice(0, 2); |
| 3 | + const hours = Number(slicedHours); |
3 | 4 | const slicedMinutes = time.slice(-2); |
| 5 | + const minutes = Number(slicedMinutes); |
| 6 | + const pattern = /^\d{2}:\d{2}$/; |
4 | 7 |
|
5 | | - if (hours === 0) { |
6 | | - return `12:${slicedMinutes} am`; |
7 | | - } else if (hours > 1 && hours <= 11) { |
8 | | - return `0${hours}:${slicedMinutes} am`; |
9 | | - } else if (hours === 12) { |
10 | | - return `12:${slicedMinutes} pm`; |
11 | | - } else if (hours > 12 && hours <= 21) { |
12 | | - return `0${hours - 12}:${slicedMinutes} pm`; |
13 | | - } else if (hours === 22 || hours === 23) { |
14 | | - return `${hours - 12}:${slicedMinutes} pm`; |
| 8 | + if (typeof time === "string" && pattern.test(time)) { |
| 9 | + if (minutes < 60) { |
| 10 | + if (hours < 24) { |
| 11 | + if (hours === 0) { |
| 12 | + return `12:${slicedMinutes} am`; |
| 13 | + } else if (hours === 12) { |
| 14 | + return `${hours}:${slicedMinutes} pm`; |
| 15 | + } else if (hours > 12) { |
| 16 | + return `${(hours - 12).toString().padStart(2, "0")}:${slicedMinutes} pm`; |
| 17 | + } else { |
| 18 | + return `${time} am`; |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + return `Please check your HH input must be less than 24`; |
| 23 | + } |
| 24 | + return `Please check your MM input must be less than 60`; |
15 | 25 | } |
| 26 | + return `Please check your format input must be 'HH:MM'`; |
16 | 27 | } |
17 | 28 |
|
18 | 29 | export { formatAs12HourClock }; |
0 commit comments