Skip to content

Commit 083a9d2

Browse files
committed
add and test formatAs12HourClock function with passing assertions
1 parent a451eda commit 083a9d2

File tree

1 file changed

+52
-1
lines changed

1 file changed

+52
-1
lines changed

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

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
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-
function formatAs12HourClock(time) {
5+
/*function formatAs12HourClock(time) {
66
const hours = Number(time.slice(0, 2));
77
if (hours > 12) {
88
return `${hours - 12}:00 pm`;
@@ -22,4 +22,55 @@ const targetOutput2 = "11:00 pm";
2222
console.assert(
2323
currentOutput2 === targetOutput2,
2424
`current output: ${currentOutput2}, target output: ${targetOutput2}`
25+
); */
26+
27+
// The function ignores the minutes and did'not handle midnight (00:00) or noon (12:00) properly.
28+
// Better version:
29+
function formatAs12HourClock(time) {
30+
const hours = Number(time.slice(0, 2));
31+
const minutes = time.slice(3, 5);
32+
33+
if (hours == 0) return `12:${minutes} am`;
34+
if (hours < 12) return `${time} am`;
35+
if (hours === 12) return `${time} pm`;
36+
37+
return `${hours - 12}:${minutes} pm`;
38+
}
39+
const currentOutput1 = formatAs12HourClock("08:00");
40+
const targetOutput1 = "08:00 am";
41+
console.assert(
42+
currentOutput1 === targetOutput1,
43+
`current output: ${currentOutput1}, target output: ${targetOutput1}`
2544
);
45+
// Test failed: due to a typo
46+
const currentOutput2 = formatAs12HourClock("23:00");
47+
const targetOutput2 = "11:00 pm";
48+
console.assert(
49+
currentOutput2 === targetOutput2,
50+
`current output: ${currentOutput2}, target output: ${targetOutput2}`
51+
52+
);
53+
54+
const currentOutput3 = formatAs12HourClock("13:00");
55+
const targetOutput3 = "1:00 pm";
56+
console.assert(
57+
currentOutput3 === targetOutput3,
58+
`current output: ${currentOutput3} target output: {targetOutput3}`
59+
);
60+
61+
const currentOutput4 = formatAs12HourClock("15:00");
62+
const targetOutput4 = "3:00 pm";
63+
console.assert(
64+
currentOutput4 === targetOutput4,
65+
`current output: ${currentOutput4} target output: {targetOutput4}`
66+
);
67+
68+
console.log(formatAs12HourClock("08:00"));
69+
console.log(formatAs12HourClock("23:00"));
70+
console.log(formatAs12HourClock("15:00"));
71+
console.assert(formatAs12HourClock("00:00") === "12:00 am");
72+
console.assert(formatAs12HourClock("12:00") === "12:00 pm");
73+
74+
// The test passed, so my function gave the expected results.
75+
// All the console.assert() tests passed.
76+
// formatAs12HourClock() function works correctly for the inputs I tested.

0 commit comments

Comments
 (0)