Skip to content

Commit 6fc17ad

Browse files
committed
Implement formatAs12HourClock function with input validation and time formatting
1 parent bfbaf1b commit 6fc17ad

1 file changed

Lines changed: 17 additions & 0 deletions

File tree

‎Sprint-3/5-stretch-extend/format-time.js‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,20 @@ console.assert(
2424
`current output: ${currentOutput2}, target output: ${targetOutput2}`
2525
);*/
2626

27+
function formatAs12HourClock(time){
28+
if (typeof time != "string"){
29+
throw new Error (`Expected a string in "HH:MM" format, got ${typeof time}`);
30+
}
31+
const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(time);
32+
if(!match){
33+
throw new RangeError(`Invalid time "${time}": expected 24-hour "HH:MM" (00:00 to 23:59)`);
34+
}
35+
36+
const hours = Number(match[1]);
37+
const minutes = match[2];
38+
const period = hours < 12 ? "am" : "pm";
39+
const hours12 = hours % 12 === 0 ? 12 : hours % 12;
40+
41+
return `${String(hours12).padStart(2, "0")}:${minutes} ${period}`;
42+
}
43+
console.log(formatAs12HourClock("23:20"))

0 commit comments

Comments
 (0)