Skip to content

Commit 4076a9a

Browse files
committed
function fixed and tested
1 parent d1cb728 commit 4076a9a

2 files changed

Lines changed: 34 additions & 9 deletions

File tree

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,23 @@
1-
function formatAs12HourClock(time) {
1+
//Think of as many edge-cases as you can with this code.
2+
// Write tests for all of them, and fix this code so that it works correctly for all valid inputs.
3+
// You don't need to worry about invalid inputs (e.g. `"25:00"`).
24

5+
function formatAs12HourClock(time) {
36
const hours = Number(time.slice(0, 2));
7+
const minutes = Number(time.slice(3, 5));
8+
9+
const paddedHours = hours.toString().padStart(2, "0");
10+
const paddedMinutes = minutes.toString().padStart(2, "0");
411

512
if (hours > 12) {
6-
return `${hours - 12}:00 pm`;
13+
return `${(hours - 12).toString().padStart(2, "0")}:${paddedMinutes} pm`;
14+
} else if (hours === 12) {
15+
return `${paddedHours}:${paddedMinutes} pm`;
16+
} else if (hours === 0) {
17+
return `12:${paddedMinutes} am`;
18+
} else {
19+
return `${paddedHours}:${paddedMinutes} am`;
720
}
8-
return `${time} am`;
921
}
1022

11-
export {formatAs12HourClock};
23+
export { formatAs12HourClock };
Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,24 @@
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", function () {
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", function () {
10+
assert.equal(formatAs12HourClock("08:00"), "08:00 am");
1111
});
12+
13+
//if input is equal to "00:00"
14+
test(`can correctly convert input of "00:00"`, () =>
15+
assert.equal(formatAs12HourClock("00:00"), "12:00 am"));
16+
//if input is equal to "12:00"
17+
test(`can correctly convert input of "12:00"`, () =>
18+
assert.equal(formatAs12HourClock("12:00"), "12:00 pm"));
19+
//if input is equal to " 07:23"
20+
test(`can correctly convert minutes`, () =>
21+
assert.equal(formatAs12HourClock("17:23"), "05:23 pm"));
22+
// test with leading zeros
23+
test("can correctly display with leading zeros", () =>
24+
assert.equal(formatAs12HourClock("03:07"), "03:07 am"));

0 commit comments

Comments
 (0)