|
6 | 6 | // You should call this function a number of times to check it works for different inputs |
7 | 7 |
|
8 | 8 | function toPounds(penceString) { |
9 | | - // return the price in pounds |
| 9 | + // return the price in pounds |
10 | 10 |
|
11 | | - // I took the code and made it as a function called toPounds with a parameter called penceString, |
12 | | - // but after reviewing the code in Ai I noticed i have to add something called defensive programming, |
13 | | - // to make sure the input is following the format of a string with a number followed by the letter p, |
14 | | - // so I will add an if statement to check if the input is valid and if not, using endWith() method and then return an error message. |
| 11 | + // I took the code and made it as a function called toPounds with a parameter called penceString, |
| 12 | + // but after reviewing the code in Ai I noticed i have to add something called defensive programming, |
| 13 | + // to make sure the input is following the format of a string with a number followed by the letter p, |
| 14 | + // so I will add an if statement to check if the input is valid and if not, using endWith() method and then return an error message. |
15 | 15 |
|
16 | | - |
17 | | - if (!penceString.endsWith("p")) { |
| 16 | + if (!penceString.endsWith("p")) { |
18 | 17 | return "Error: Please enter a valid pence format (e.g., '399p')"; |
19 | | -} |
| 18 | + } |
20 | 19 |
|
21 | | - const penceStringWithoutTrailingP = penceString.substring( |
22 | | - 0, |
23 | | - penceString.length - 1 |
24 | | -); |
| 20 | + const penceStringWithoutTrailingP = penceString.substring( |
| 21 | + 0, |
| 22 | + penceString.length - 1 |
| 23 | + ); |
25 | 24 |
|
26 | | -const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); |
| 25 | + const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); |
27 | 26 |
|
28 | | -const pounds = paddedPenceNumberString.substring( |
29 | | - 0, |
30 | | - paddedPenceNumberString.length - 2 |
31 | | -); |
| 27 | + const pounds = paddedPenceNumberString.substring( |
| 28 | + 0, |
| 29 | + paddedPenceNumberString.length - 2 |
| 30 | + ); |
32 | 31 |
|
33 | | -const pence = paddedPenceNumberString |
34 | | - .substring(paddedPenceNumberString.length - 2) |
35 | | - .padEnd(2, "0"); |
| 32 | + const pence = paddedPenceNumberString |
| 33 | + .substring(paddedPenceNumberString.length - 2) |
| 34 | + .padEnd(2, "0"); |
36 | 35 |
|
37 | | -return (`£${pounds}.${pence}`); |
| 36 | + return `£${pounds}.${pence}`; |
38 | 37 | } |
39 | 38 |
|
40 | 39 | console.log(toPounds("399p")); |
41 | 40 | console.log(toPounds("5p")); |
42 | 41 | console.log(toPounds("abc")); |
43 | | - |
0 commit comments