Skip to content

Commit eeff899

Browse files
committed
Correct 12-hour clock formatting and add comprehensive tests
1 parent 01a1ced commit eeff899

File tree

1 file changed

+30
-19
lines changed

1 file changed

+30
-19
lines changed

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

Lines changed: 30 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,36 @@
1-
// This is the latest solution to the problem from the prep.
2-
// Make sure to do the prep before you do the coursework
3-
// 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.
4-
51
function formatAs12HourClock(time) {
62
const hours = Number(time.slice(0, 2));
7-
if (hours > 12) {
8-
return `${hours - 12}:00 pm`;
3+
const minutes = time.slice(3, 5);
4+
5+
if (hours === 0) {
6+
// midnight
7+
return `12:${minutes} am`;
8+
} else if (hours === 12) {
9+
// noon
10+
return `12:${minutes} pm`;
11+
} else if (hours > 12) {
12+
return `${hours - 12}:${minutes} pm`;
13+
} else {
14+
// 1am to 11am
15+
return `${time} am`;
916
}
10-
return `${time} am`;
1117
}
1218

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-
);
19+
// Tests:
20+
const tests = [
21+
{ input: "00:00", expected: "12:00 am" },
22+
{ input: "08:00", expected: "08:00 am" },
23+
{ input: "12:00", expected: "12:00 pm" },
24+
{ input: "15:30", expected: "3:30 pm" },
25+
{ input: "23:59", expected: "11:59 pm" },
26+
{ input: "11:15", expected: "11:15 am" },
27+
];
28+
29+
tests.forEach(({ input, expected }) => {
30+
const output = formatAs12HourClock(input);
31+
console.assert(
32+
output === expected,
33+
`FAIL: input=${input}, output=${output}, expected=${expected}`
34+
);
35+
});
1936

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

0 commit comments

Comments
 (0)