Skip to content

Commit a24cdf8

Browse files
Tested all edge cases and fixed function
1 parent 770601e commit a24cdf8

2 files changed

Lines changed: 27 additions & 9 deletions

File tree

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,21 @@
11
function formatAs12HourClock(time) {
2+
const [hoursStr, minutesStr] = time.split(":");
3+
const hours = Number(hoursStr);
4+
const minutes = minutesStr ?? "00";
25

3-
const hours = Number(time.slice(0, 2));
6+
if (hours === 0) {
7+
return `12:${minutes} am`;
8+
}
9+
10+
if (hours < 12) {
11+
return `${String(hours).padStart(2, "0")}:${minutes} am`;
12+
}
413

5-
if (hours > 12) {
6-
return `${hours - 12}:00 pm`;
14+
if (hours === 12) {
15+
return `12:${minutes} pm`;
716
}
8-
return `${time} am`;
17+
18+
return `${String(hours - 12).padStart(2, "0")}:${minutes} pm`;
919
}
1020

1121
export {formatAs12HourClock};

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

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,25 @@ 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("converts midnight correctly", function() {
6+
assert.equal(formatAs12HourClock("00:00"), "12:00 am");
77
});
88

9-
test("can correctly convert morning time", function() {
9+
test("converts early morning times correctly", function() {
10+
assert.equal(formatAs12HourClock("01:00"), "01:00 am");
1011
assert.equal(formatAs12HourClock("08:00"), "08:00 am");
12+
assert.equal(formatAs12HourClock("11:59"), "11:59 am");
1113
});
1214

13-
test("can correctly convert 00:00", function() {
14-
assert.equal(formatAs12HourClock("00:00"), "12:00 am");
15+
test("converts noon correctly", function() {
16+
assert.equal(formatAs12HourClock("12:00"), "12:00 pm");
17+
assert.equal(formatAs12HourClock("12:30"), "12:30 pm");
1518
});
1619

20+
test("converts afternoon and evening times correctly", function() {
21+
assert.equal(formatAs12HourClock("13:00"), "01:00 pm");
22+
assert.equal(formatAs12HourClock("18:45"), "06:45 pm");
23+
assert.equal(formatAs12HourClock("23:00"), "11:00 pm");
24+
});
1725

1826

0 commit comments

Comments
 (0)