Skip to content

Commit 5026ab3

Browse files
committed
Sprint 2 extend: add edge case tests and fix 12-hour clock conversion
1 parent 400e5a8 commit 5026ab3

File tree

1 file changed

+52
-5
lines changed

1 file changed

+52
-5
lines changed

Sprint-2/5-stretch-extend/format-time.js

Lines changed: 52 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,17 @@
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

55
function formatAs12HourClock(time) {
6-
const hours = Number(time.slice(0, 2));
7-
if (hours > 12) {
8-
return `${hours - 12}:00 pm`;
9-
}
10-
return `${time} am`;
6+
const hours24 = Number(time.slice(0, 2));
7+
const minutes = time.slice(3, 5);
8+
9+
const period = hours24 >= 12 ? "pm" : "am";
10+
11+
let hours12 = hours24 % 12;
12+
if (hours12 === 0) hours12 = 12;
13+
14+
const paddedHours12 = String(hours12).padStart(2, "0");
15+
16+
return `${paddedHours12}:${minutes} ${period}`;
1117
}
1218

1319
const currentOutput = formatAs12HourClock("08:00");
@@ -23,3 +29,44 @@ console.assert(
2329
currentOutput2 === targetOutput2,
2430
`current output: ${currentOutput2}, target output: ${targetOutput2}`
2531
);
32+
33+
34+
35+
// --------------------
36+
// Extra tests (edge cases + minutes)
37+
// --------------------
38+
39+
// Midnight (00:00) should be 12:00 am
40+
console.assert(
41+
formatAs12HourClock("00:00") === "12:00 am",
42+
`current output: ${formatAs12HourClock("00:00")}, target output: 12:00 am`
43+
);
44+
45+
// Noon (12:00) should be 12:00 pm
46+
console.assert(
47+
formatAs12HourClock("12:00") === "12:00 pm",
48+
`current output: ${formatAs12HourClock("12:00")}, target output: 12:00 pm`
49+
);
50+
51+
// Minutes must be preserved
52+
console.assert(
53+
formatAs12HourClock("23:15") === "11:15 pm",
54+
`current output: ${formatAs12HourClock("23:15")}, target output: 11:15 pm`
55+
);
56+
57+
console.assert(
58+
formatAs12HourClock("13:05") === "01:05 pm",
59+
`current output: ${formatAs12HourClock("13:05")}, target output: 01:05 pm`
60+
);
61+
62+
// Morning should stay am
63+
console.assert(
64+
formatAs12HourClock("01:09") === "01:09 am",
65+
`current output: ${formatAs12HourClock("01:09")}, target output: 01:09 am`
66+
);
67+
68+
// Boundary just before noon
69+
console.assert(
70+
formatAs12HourClock("11:59") === "11:59 am",
71+
`current output: ${formatAs12HourClock("11:59")}, target output: 11:59 am`
72+
);

0 commit comments

Comments
 (0)