22// Make sure to do the prep before you do the coursework
33// Your task is to write tests for as many different groups of input data or edge cases as you can, and fix any bugs you find.
44
5+ // original code:
6+ // function formatAs12HourClock(time) {
7+ // const hours = Number(time.slice(0, 2));
8+ // if (hours > 12) {
9+ // return `${hours - 12}:00 pm`;
10+ // }
11+ // return `${time} am`;
12+ // }
13+
14+ // const currentOutput = formatAs12HourClock("08:00");
15+ // const targetOutput = "08:00 am";
16+ // console.assert(
17+ // currentOutput === targetOutput,
18+ // `current output: ${currentOutput}, target output: ${targetOutput}`
19+ // );
20+
21+ // const currentOutput2 = formatAs12HourClock("23:00");
22+ // const targetOutput2 = "11:00 pm";
23+ // console.assert(
24+ // currentOutput2 === targetOutput2,
25+ // `current output: ${currentOutput2}, target output: ${targetOutput2}`
26+ // );
27+
28+ // my code:
529function formatAs12HourClock ( time ) {
630 const hours = Number ( time . slice ( 0 , 2 ) ) ;
7- if ( hours > 12 ) {
8- return `${ hours - 12 } :00 pm` ;
31+ if ( hours >= 12 ) {
32+ return `${ hours - 12 } :${ time . slice ( 3 ) } pm` ;
933 }
10- return `${ time } am` ;
34+ return `${ time } : ${ time . slice ( 3 ) } am` ;
1135}
1236
13- const currentOutput = formatAs12HourClock ( "08:00" ) ;
14- const targetOutput = "08:00 am" ;
15- console . assert (
16- currentOutput === targetOutput ,
17- `current output: ${ currentOutput } , target output: ${ targetOutput } `
18- ) ;
37+ const cases = [
38+ { input : "00:00" , expected : "12:00 am" } , // midnight
39+ { input : "01:00" , expected : "01:00 am" } ,
40+ { input : "02:00" , expected : "02:00 am" } , // your failing test
41+ { input : "09:00" , expected : "09:00 am" } ,
42+ { input : "11:59" , expected : "11:59 am" } ,
43+ { input : "12:00" , expected : "12:00 pm" } , // noon
44+ { input : "12:30" , expected : "12:30 pm" } ,
45+ { input : "13:00" , expected : "01:00 pm" } ,
46+ { input : "23:00" , expected : "11:00 pm" } , // your other test
47+ { input : "23:59" , expected : "11:59 pm" } ,
48+ ] ;
1949
20- const currentOutput2 = formatAs12HourClock ( "23:00" ) ;
21- const targetOutput2 = "11:00 pm" ;
22- console . assert (
23- currentOutput2 === targetOutput2 ,
24- `current output: ${ currentOutput2 } , target output: ${ targetOutput2 } `
25- ) ;
50+ function runTests ( cases ) {
51+ let passed = 0 ;
52+ for ( const { input, expected } of cases ) {
53+ const actual = formatAs12HourClock ( input ) ;
54+ const ok = actual === expected ;
55+ if ( ok ) passed ++ ;
56+ console . log (
57+ `${ ok ? "PASS" : "FAIL" } input: ${ input } expected: ${ expected } actual: ${ actual } `
58+ ) ;
59+ }
60+ console . log ( `\n${ passed } /${ cases . length } passed` ) ;
61+ }
62+ runTests ( cases ) ;
0 commit comments