Skip to content

Commit 008bc6e

Browse files
Fix 12-hour clock: pad hours and handle midnight and noon
1 parent 42903a4 commit 008bc6e

1 file changed

Lines changed: 5 additions & 11 deletions

File tree

‎Sprint-3/5-stretch-extend/format-time.js‎

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,14 @@
11
// This is the latest solution to the problem from the prep.
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.
4-
54
function formatAs12HourClock(time) {
65
const hours = Number(time.slice(0, 2));
76
const minutes = time.slice(3);
87

9-
if (hours === 0) {
10-
return `12:${minutes} am`;
11-
} else if (hours === 12) {
12-
return `12:${minutes} pm`;
13-
} else if (hours > 12) {
14-
return `${hours - 12}:${minutes} pm`;
15-
} else {
16-
return `${hours}:${minutes} am`;
17-
}
8+
const period = hours >= 12 ? "pm" : "am";
9+
const hours12 = hours % 12 === 0 ? 12 : hours % 12;
10+
11+
return `${String(hours12).padStart(2, "0")}:${minutes} ${period}`;
1812
}
1913

2014
// Original tests
@@ -50,7 +44,7 @@ console.assert(
5044

5145
// Edge case: PM time with non-zero minutes (checks minutes aren't lost)
5246
const currentOutput5 = formatAs12HourClock("13:45");
53-
const targetOutput5 = "1:45 pm";
47+
const targetOutput5 = "01:45 pm";
5448
console.assert(
5549
currentOutput5 === targetOutput5,
5650
`current output: ${currentOutput5}, target output: ${targetOutput5}`

0 commit comments

Comments
 (0)