Skip to content

Commit 6e75e0c

Browse files
committed
Fix 12-hour clock edge cases
Cover valid time boundaries and preserve minutes across conversion.
1 parent 29ef74a commit 6e75e0c

2 files changed

Lines changed: 31 additions & 10 deletions

File tree

‎format-clock-edge-cases/timeConverter.js‎

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

59
if (hours > 12) {
6-
return `${hours - 12}:00 pm`;
10+
return `${hours - 12}:${minutes} pm`;
711
}
12+
13+
if (hours === 12) {
14+
return `${time} pm`;
15+
}
16+
817
return `${time} am`;
918
}
1019

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,23 @@
1-
import {formatAs12HourClock} from "./timeConverter.js";
2-
import assert from "node:assert";
1+
import { formatAs12HourClock } from "./timeConverter.js";
2+
import assert from "node:assert/strict";
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+
const cases = [
6+
["00:00", "12:00 am"],
7+
["00:01", "12:01 am"],
8+
["01:05", "01:05 am"],
9+
["08:00", "08:00 am"],
10+
["11:59", "11:59 am"],
11+
["12:00", "12:00 pm"],
12+
["12:34", "12:34 pm"],
13+
["13:00", "1:00 pm"],
14+
["15:45", "3:45 pm"],
15+
["23:00", "11:00 pm"],
16+
["23:59", "11:59 pm"],
17+
];
818

9-
test("can correctly convert morning time", function() {
10-
assert.equal(formatAs12HourClock("08:00"), "08:00 am");
11-
});
19+
for (const [time, expected] of cases) {
20+
test(`${time} converts to ${expected}`, () => {
21+
assert.equal(formatAs12HourClock(time), expected);
22+
});
23+
}

0 commit comments

Comments
 (0)