File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11function formatAs12HourClock ( time ) {
22
33 const hours = Number ( time . slice ( 0 , 2 ) ) ;
4+ const minutes = time . slice ( 3 , 5 ) ;
5+ const paddedPMHours = ( hours - 12 ) . toString ( ) . padStart ( 2 , "0" ) ;
6+ const paddedAMHours = hours . toString ( ) . padStart ( 2 , "0" ) ;
47
5- if ( hours > 12 ) {
6- return `${ hours - 12 } :00 pm ` ;
8+ if ( hours < 0 || hours > 24 || minutes < 0 || minutes > 59 ) {
9+ return `Invalid time ` ;
710 }
8- return `${ time } am` ;
11+ if ( hours === 0 ) {
12+ return `12:${ minutes } AM` ;
13+ }
14+ if ( hours === 12 ) {
15+ return `12:${ minutes } PM` ;
16+ }
17+ if ( hours === 24 ) {
18+ return `12:${ minutes } AM` ;
19+ }
20+ if ( hours > 12 ) {
21+ return `${ paddedPMHours } :${ minutes } PM` ;
22+ }
23+ return `${ paddedAMHours } :${ minutes } AM` ;
924}
1025
1126export { formatAs12HourClock } ;
Original file line number Diff line number Diff line change 1- import { formatAs12HourClock } from "./timeConverter.js" ;
1+ import { formatAs12HourClock } from "./timeConverter.js" ;
22import assert from "node:assert" ;
33import 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+ [ "08:00" , "08:00 AM" ] ,
7+ [ "23:00" , "11:00 PM" ] ,
8+ [ "15:30" , "03:30 PM" ] ,
9+ [ "12:10" , "12:10 PM" ] ,
10+ [ "08:45" , "08:45 AM" ] ,
11+ [ "09:05" , "09:05 AM" ] ,
12+ [ "17:45" , "05:45 PM" ] ,
13+ [ "00:00" , "12:00 AM" ] ,
14+ [ "11:59" , "11:59 AM" ] ,
15+ [ "23:59" , "11:59 PM" ] ,
16+ ] ;
817
9- test ( "can correctly convert morning time" , function ( ) {
10- assert . equal ( formatAs12HourClock ( "08:00" ) , "08:00 am" ) ;
18+ cases . forEach ( ( [ input , expected ] ) => {
19+ const output = formatAs12HourClock ( input ) ;
20+ if ( output === expected ) {
21+ console . log ( `✅ ${ input } → returned "${ output } "` ) ;
22+ } else {
23+ console . error ( `❌ ${ input } → returned "${ output } ", expected "${ expected } "` ) ;
24+ }
1125} ) ;
You can’t perform that action at this time.
0 commit comments