Skip to content

Commit f016ea8

Browse files
committed
Fix formatAs12HourClock edge cases and add tests
1 parent 29ef74a commit f016ea8

2 files changed

Lines changed: 37 additions & 12 deletions

File tree

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,17 @@
1-
function formatAs12HourClock(time) {
1+
// function receives a string representing time in 24-hour format as an argument
22

3+
function formatAs12HourClock(time) {
34
const hours = Number(time.slice(0, 2));
5+
const minutes = time.slice(3, 5);
46

5-
if (hours > 12) {
6-
return `${hours - 12}:00 pm`;
7+
const period = hours >= 12 ? "pm" : "am";
8+
9+
let displayHour = hours % 12;
10+
if (displayHour === 0) {
11+
displayHour = 12;
712
}
8-
return `${time} am`;
13+
14+
return `${displayHour}:${minutes} ${period}`;
915
}
1016

11-
export {formatAs12HourClock};
17+
export { formatAs12HourClock };
Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,30 @@
1-
import {formatAs12HourClock} from "./timeConverter.js";
1+
import { formatAs12HourClock } from "./timeConverter.js";
22
import assert from "node:assert";
33
import test from "node:test";
44

5-
test("correctly convert time after 12:00", function(){
6-
assert.equal(formatAs12HourClock("23:00"), "11:00 pm");
7-
});
5+
test("correctly convert time after 12:00", () =>
6+
assert.equal(formatAs12HourClock("23:00"), "11:00 pm"));
87

9-
test("can correctly convert morning time", function() {
10-
assert.equal(formatAs12HourClock("08:00"), "08:00 am");
11-
});
8+
test("can correctly convert morning time", () =>
9+
assert.equal(formatAs12HourClock("08:00"), "8:00 am"));
10+
11+
test("can correctly convert midnight", () =>
12+
assert.equal(formatAs12HourClock("00:00"), "12:00 am"));
13+
14+
test("noon is pm", () =>
15+
assert.equal(formatAs12HourClock("12:00"), "12:00 pm"));
16+
17+
test("noon with minutes", () =>
18+
assert.equal(formatAs12HourClock("12:45"), "12:45 pm"));
19+
20+
test("afternoon keeps minutes", () =>
21+
assert.equal(formatAs12HourClock("13:30"), "1:30 pm"));
22+
23+
test("evening keeps minutes", () =>
24+
assert.equal(formatAs12HourClock("23:15"), "11:15 pm"));
25+
26+
test("midnight with minutes", () =>
27+
assert.equal(formatAs12HourClock("00:30"), "12:30 am"));
28+
29+
test("just before noon", () =>
30+
assert.equal(formatAs12HourClock("11:59"), "11:59 am"));

0 commit comments

Comments
 (0)