Skip to content

Commit 7afee0c

Browse files
committed
Complete Sprint 3 section 5: extend
1 parent 8d171ae commit 7afee0c

1 file changed

Lines changed: 23 additions & 16 deletions

File tree

‎Sprint-3/5-stretch-extend/format-time.js‎

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,31 @@
22
// Make sure to do the prep before you do the coursework
33
// 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.
44

5+
const assert = require("node:assert/strict");
6+
57
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");
910
}
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}`;
1118
}
1219

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);
1931

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

Comments
 (0)