|
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 | +const assert = require("node:assert/strict"); |
| 6 | + |
5 | 7 | function formatAs12HourClock(time) { |
6 | | - const hours = Number(time.slice(0, 2)); |
7 | | - if (hours > 12) { |
8 | | - return `${hours - 12}:00 pm`; |
| 8 | + if (typeof time !== "string" || !/^(?:[01]\d|2[0-3]):[0-5]\d$/.test(time)) { |
| 9 | + throw new RangeError("time must be a valid 24-hour time in HH:MM format"); |
9 | 10 | } |
10 | | - return `${time} am`; |
| 11 | + |
| 12 | + const hours = Number(time.slice(0, 2)); |
| 13 | + const displayHours = String(hours % 12 || 12).padStart(2, "0"); |
| 14 | + const minutes = time.slice(3); |
| 15 | + const period = hours < 12 ? "am" : "pm"; |
| 16 | + |
| 17 | + return `${displayHours}:${minutes} ${period}`; |
11 | 18 | } |
12 | 19 |
|
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 | | -); |
| 20 | +assert.equal(formatAs12HourClock("00:00"), "12:00 am"); |
| 21 | +assert.equal(formatAs12HourClock("00:05"), "12:05 am"); |
| 22 | +assert.equal(formatAs12HourClock("08:00"), "08:00 am"); |
| 23 | +assert.equal(formatAs12HourClock("11:59"), "11:59 am"); |
| 24 | +assert.equal(formatAs12HourClock("12:00"), "12:00 pm"); |
| 25 | +assert.equal(formatAs12HourClock("12:45"), "12:45 pm"); |
| 26 | +assert.equal(formatAs12HourClock("13:07"), "01:07 pm"); |
| 27 | +assert.equal(formatAs12HourClock("23:59"), "11:59 pm"); |
| 28 | +assert.throws(() => formatAs12HourClock("24:00"), RangeError); |
| 29 | +assert.throws(() => formatAs12HourClock("12:60"), RangeError); |
| 30 | +assert.throws(() => formatAs12HourClock("8:00"), RangeError); |
19 | 31 |
|
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 | | -); |
| 32 | +console.log("All formatAs12HourClock tests passed."); |
0 commit comments