Skip to content

Commit 7d4c0fb

Browse files
committed
Refactor formatAs12HourClock function to improve time formatting logic and add comprehensive test cases
1 parent 80f3a4f commit 7d4c0fb

1 file changed

Lines changed: 31 additions & 3 deletions

File tree

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

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,24 @@
44

55
function formatAs12HourClock(time) {
66
const hours = Number(time.slice(0, 2));
7-
if (hours > 12) {
8-
return `${hours - 12}:00 pm`;
7+
const minutes = time.slice(3, 5);
8+
if (hours >= 12) {
9+
const pmHours = String(hours === 12 ? 12 : hours - 12).padStart(2, "0");
10+
return `${pmHours}:${minutes} pm`;
11+
}
12+
const amHours = String(hours === 0 ? 12 : hours).padStart(2, "0");
13+
return `${amHours}:${minutes} am`;
14+
}
15+
16+
function runTest(description, input, expected) {
17+
const result = formatAs12HourClock(input);
18+
console.assert(
19+
result === expected,
20+
`Test failed for ${description}: expected ${expected}, got ${result}`
21+
);
22+
if (result === expected) {
23+
console.log(`Test passed for ${description}`);
924
}
10-
return `${time} am`;
1125
}
1226

1327
const currentOutput = formatAs12HourClock("08:00");
@@ -23,3 +37,17 @@ console.assert(
2337
currentOutput2 === targetOutput2,
2438
`current output: ${currentOutput2}, target output: ${targetOutput2}`
2539
);
40+
41+
//== Additional Test Cases =//
42+
43+
// Test case for standard AM time
44+
runTest("Standard early morning", "08:00", "08:00 am");
45+
runTest("standard late morning", "11:30", "11:30 am");
46+
47+
// Test case for standard PM time
48+
runTest("Standard afternoon", "13:15", "01:15 pm");
49+
runTest("Standard evening", "20:45", "08:45 pm");
50+
51+
// Test case for 12-hour threshold2
52+
runTest("Exact Noon (12:00)", "12:00", "12:00 pm");
53+
runTest("Exact Midnight", "00:00", "12:00 am");

0 commit comments

Comments
 (0)