Skip to content

Commit 86827f4

Browse files
committed
complete ex format-time.js
1 parent f80713c commit 86827f4

1 file changed

Lines changed: 29 additions & 6 deletions

File tree

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

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,46 @@
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

55
function formatAs12HourClock(time) {
6-
const hours = Number(time.slice(0, 2));
7-
if (hours > 12) {
8-
return `${hours - 12}:00 pm`;
6+
const [hoursString, minutesString = "00"] = time.split(":");
7+
const hours = Number(hoursString);
8+
const minutes = minutesString;
9+
10+
let suffix = "am";
11+
if (hours >= 12) {
12+
suffix = "pm";
13+
}
14+
let formattedHours = hours % 12;
15+
16+
if (formattedHours === 0) {
17+
formattedHours = 12;
918
}
10-
return `${time} am`;
19+
return `${formattedHours}:${minutes} ${suffix}`;
1120
}
1221

1322
const currentOutput = formatAs12HourClock("08:00");
1423
const targetOutput = "08:00 am";
1524
console.assert(
1625
currentOutput === targetOutput,
17-
`current output: ${currentOutput}, target output: ${targetOutput}`
26+
`current output: ${currentOutput}, target output: ${targetOutput}`,
1827
);
1928

2029
const currentOutput2 = formatAs12HourClock("23:00");
2130
const targetOutput2 = "11:00 pm";
2231
console.assert(
2332
currentOutput2 === targetOutput2,
24-
`current output: ${currentOutput2}, target output: ${targetOutput2}`
33+
`current output: ${currentOutput2}, target output: ${targetOutput2}`,
34+
);
35+
const noonOutput = formatAs12HourClock("12:00");
36+
const noonTarget = "12:00 pm";
37+
console.assert(
38+
noonOutput === noonTarget,
39+
`current output: ${noonOutput}, target output: ${noonTarget}`,
40+
);
41+
42+
const midnightOutput = formatAs12HourClock("00:00");
43+
const midnightTarget = "12:00 am";
44+
console.assert(
45+
midnightOutput === midnightTarget,
46+
`current output: ${midnightOutput}, target output: ${midnightTarget}`,
2547
);
48+
console.log("All tests passed");

0 commit comments

Comments
 (0)