Skip to content

Commit decced1

Browse files
committed
Improve time conversion logic and add full tests
1 parent 4403ed4 commit decced1

1 file changed

Lines changed: 61 additions & 0 deletions

File tree

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

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,64 @@ console.assert(
2323
currentOutput2 === targetOutput2,
2424
`current output: ${currentOutput2}, target output: ${targetOutput2}`
2525
);
26+
27+
// Midnight
28+
console.assert(
29+
formatAs12HourClock("00:00") === "12:00 am",
30+
"00:00 should be 12:00 am"
31+
);
32+
33+
// Noon
34+
console.assert(
35+
formatAs12HourClock("12:00") === "12:00 pm",
36+
"12:00 should be 12:00 pm"
37+
);
38+
39+
// Minutes included
40+
console.assert(
41+
formatAs12HourClock("14:45") === "2:45 pm",
42+
"14:45 should be 2:45 pm"
43+
);
44+
45+
// Single-digit hour AM
46+
console.assert(
47+
formatAs12HourClock("09:30") === "9:30 am",
48+
"09:30 should be 9:30 am"
49+
);
50+
51+
// Single-digit hour PM
52+
console.assert(
53+
formatAs12HourClock("13:05") === "1:05 pm",
54+
"13:05 should be 1:05 pm"
55+
);
56+
57+
// Edge: 12:59 PM
58+
console.assert(
59+
formatAs12HourClock("12:59") === "12:59 pm",
60+
"12:59 should be 12:59 pm"
61+
);
62+
63+
// Edge: 00:59 AM
64+
console.assert(
65+
formatAs12HourClock("00:59") === "12:59 am",
66+
"00:59 should be 12:59 am"
67+
);
68+
69+
function formatAs12HourClock(time) {
70+
const [hourStr, minuteStr] = time.split(":");
71+
let hours = Number(hourStr);
72+
const minutes = minuteStr;
73+
74+
let period = "am";
75+
76+
if (hours === 0) {
77+
hours = 12; // midnight
78+
} else if (hours === 12) {
79+
period = "pm"; // noon
80+
} else if (hours > 12) {
81+
hours -= 12;
82+
period = "pm";
83+
}
84+
85+
return `${hours}:${minutes} ${period}`;
86+
}

0 commit comments

Comments
 (0)