44// You should call this function a number of times to check it works for different inputs
55
66function toPounds ( penceString ) {
7- penceString = String ( penceString ) ; // ensures input is treated as a string even if number is inputted
8- // const penceStringWithoutTrailingP = penceString.substring(
9- let penceStringWithoutTrailingP = penceString ;
10- if ( penceString . endsWith ( "p" ) ) {
11- penceStringWithoutTrailingP = penceString . substring ( 0 , penceString . length - 1 ) ;
12- } // This prevents the last characters from being sliced off if there is no p.
7+ penceString = String ( penceString ) ; // ensures input is treated as a string even if number is inputted
8+ // const penceStringWithoutTrailingP = penceString.substring(
9+ let penceStringWithoutTrailingP = penceString ;
10+ if ( penceString . endsWith ( "p" ) ) {
11+ penceStringWithoutTrailingP = penceString . substring (
12+ 0 ,
13+ penceString . length - 1
14+ ) ;
15+ } // This prevents the last characters from being sliced off if there is no p.
1316
14- const paddedPenceNumberString = penceStringWithoutTrailingP . padStart ( 3 , "0" ) ;
15- const pounds = paddedPenceNumberString . substring (
16- 0 ,
17- paddedPenceNumberString . length - 2
18- ) ;
17+ const paddedPenceNumberString = penceStringWithoutTrailingP . padStart ( 3 , "0" ) ;
18+ const pounds = paddedPenceNumberString . substring (
19+ 0 ,
20+ paddedPenceNumberString . length - 2
21+ ) ;
1922
20- const pence = paddedPenceNumberString
21- . substring ( paddedPenceNumberString . length - 2 )
22- . padEnd ( 2 , "0" ) ;
23+ const pence = paddedPenceNumberString
24+ . substring ( paddedPenceNumberString . length - 2 )
25+ . padEnd ( 2 , "0" ) ;
2326
24- return `£${ pounds } .${ pence } ` ;
27+ return `£${ pounds } .${ pence } ` ;
2528}
2629console . log ( toPounds ( "481p" ) ) ;
2730console . log ( toPounds ( "50p" ) ) ;
2831console . log ( toPounds ( "5p" ) ) ;
2932console . log ( toPounds ( "0p" ) ) ;
3033console . log ( toPounds ( "12345p" ) ) ;
3134console . log ( toPounds ( "9" ) ) ; // edge case: missing 'p' at the end, returns 0 rather than error because last character is sliced off
32- // Can be fixed by changing line 8
35+ // Can be fixed by changing line 8
3336console . log ( toPounds ( "abc" ) ) ; // Works but returns nonsense value
34- console . log ( toPounds ( 123 ) ) ; // Works with number input because of line 7 converting to string
37+ console . log ( toPounds ( 123 ) ) ; // Works with number input because of line 7 converting to string
0 commit comments