Skip to content

Commit 077e02e

Browse files
committed
fix formatAs12HourClock edge cases and add tests
1 parent 29ef74a commit 077e02e

2 files changed

Lines changed: 44 additions & 8 deletions

File tree

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,19 @@
11
function formatAs12HourClock(time) {
2-
32
const hours = Number(time.slice(0, 2));
3+
const minutes = time.slice(3, 5);
4+
5+
if (hours === 0) {
6+
return `12:${minutes} am`;
7+
}
8+
9+
if (hours === 12) {
10+
return `12:${minutes} pm`;
11+
}
412

513
if (hours > 12) {
6-
return `${hours - 12}:00 pm`;
14+
return `${String(hours - 12).padStart(2, "0")}:${minutes} pm`;
715
}
816
return `${time} am`;
917
}
1018

11-
export {formatAs12HourClock};
19+
export { formatAs12HourClock };
Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,39 @@
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");
5+
test("correctly convert time after 12:00", () => {
6+
assert.equal(formatAs12HourClock("23:00"), "11:00 pm");
77
});
88

9-
test("can correctly convert morning time", function() {
10-
assert.equal(formatAs12HourClock("08:00"), "08:00 am");
9+
test("can correctly convert morning time", () => {
10+
assert.equal(formatAs12HourClock("08:00"), "08:00 am");
11+
});
12+
13+
test("handles midnight correctly", () => {
14+
assert.equal(formatAs12HourClock("00:00"), "12:00 am");
15+
});
16+
17+
test("handles noon correctly", () => {
18+
assert.equal(formatAs12HourClock("12:00"), "12:00 pm");
19+
});
20+
21+
test("handles noon with minutes", () => {
22+
assert.equal(formatAs12HourClock("12:30"), "12:30 pm");
23+
});
24+
25+
test("handles afternoon time with leading zero", () => {
26+
assert.equal(formatAs12HourClock("13:00"), "01:00 pm");
27+
});
28+
29+
test("handles afternoon time with minutes", () => {
30+
assert.equal(formatAs12HourClock("23:45"), "11:45 pm");
31+
});
32+
33+
test("handles early morning with leading zero", () => {
34+
assert.equal(formatAs12HourClock("01:00"), "01:00 am");
35+
});
36+
37+
test("handles just before noon", () => {
38+
assert.equal(formatAs12HourClock("11:59"), "11:59 am");
1139
});

0 commit comments

Comments
 (0)