11// In Sprint-1, there is a program written in interpret/to-pounds.js
2-
32// You will need to take this code and turn it into a reusable block of code.
43// You will need to declare a function called toPounds with an appropriately named parameter.
5-
64// You should call this function a number of times to check it works for different inputs
5+
6+ function 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.
13+
14+ const paddedPenceNumberString = penceStringWithoutTrailingP . padStart ( 3 , "0" ) ;
15+ const pounds = paddedPenceNumberString . substring (
16+ 0 ,
17+ paddedPenceNumberString . length - 2
18+ ) ;
19+
20+ const pence = paddedPenceNumberString
21+ . substring ( paddedPenceNumberString . length - 2 )
22+ . padEnd ( 2 , "0" ) ;
23+
24+ return `£${ pounds } .${ pence } ` ;
25+ }
26+ console . log ( toPounds ( "481p" ) ) ;
27+ console . log ( toPounds ( "50p" ) ) ;
28+ console . log ( toPounds ( "5p" ) ) ;
29+ console . log ( toPounds ( "0p" ) ) ;
30+ console . log ( toPounds ( "12345p" ) ) ;
31+ console . 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
33+ console . log ( toPounds ( "abc" ) ) ; // Works but returns nonsense value
34+ console . log ( toPounds ( 123 ) ) ; // Works with number input because of line 7 converting to string
0 commit comments