Skip to content

Commit 43aecb9

Browse files
committed
Implement 12-hour clock formatting in format-time.js
1 parent 53a906d commit 43aecb9

1 file changed

Lines changed: 29 additions & 21 deletions

File tree

Lines changed: 29 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,33 @@
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) {
6-
const hours = Number(time.slice(0, 2));
7-
if (hours > 12) {
8-
return `${hours - 12}:00 pm`;
9-
}
10-
return `${time} am`;
2+
const timeParts = time.split(":");
3+
const mins = timeParts[1].padStart(2, "0");
4+
const hoursInt = Number(timeParts[0]);
5+
if (hoursInt === 0) return `${12}:${mins} am`;
6+
if (hoursInt < 12) return `${timeParts[0].padStart(2, "0")}:${mins} am`;
7+
if (hoursInt === 12)
8+
return `${timeParts[0]}:${timeParts[1].padStart(2, "0")} pm`;
9+
return `${(hoursInt - 12).toString().padStart(2, "0")}:${mins} pm`;
1110
}
1211

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-
);
12+
console.log(formatAs12HourClock("0:0"));
13+
14+
const testValues = [
15+
["0:0", "12:00 am"],
16+
["00:00", "12:00 am"],
17+
["08:00", "08:00 am"],
18+
["8:25", "08:25 am"],
19+
["11:59", "11:59 am"],
20+
["12:00", "12:00 pm"],
21+
["12:01", "12:01 pm"],
22+
["13:00", "01:00 pm"],
23+
["16:5", "04:05 pm"],
24+
["23:00", "11:00 pm"],
25+
];
1926

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-
);
27+
for (const [input, expectedOutput] of testValues) {
28+
const actualOutput = formatAs12HourClock(input);
29+
console.assert(
30+
actualOutput === expectedOutput,
31+
`Current output is ${actualOutput}. Expected outout is ${expectedOutput}`
32+
);
33+
}

0 commit comments

Comments
 (0)