Skip to content

Commit 4896b8f

Browse files
committed
Add defensive programming to toPounds function for input validation
1 parent 6f0c4c8 commit 4896b8f

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Sprint-2/3-mandatory-implement/3-to-pounds.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,40 @@
44
// You will need to declare a function called toPounds with an appropriately named parameter.
55

66
// You should call this function a number of times to check it works for different inputs
7+
8+
function toPounds(penceString) {
9+
// return the price in pounds
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.
15+
16+
17+
if (!penceString.endsWith("p")) {
18+
return "Error: Please enter a valid pence format (e.g., '399p')";
19+
}
20+
21+
const penceStringWithoutTrailingP = penceString.substring(
22+
0,
23+
penceString.length - 1
24+
);
25+
26+
const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0");
27+
28+
const pounds = paddedPenceNumberString.substring(
29+
0,
30+
paddedPenceNumberString.length - 2
31+
);
32+
33+
const pence = paddedPenceNumberString
34+
.substring(paddedPenceNumberString.length - 2)
35+
.padEnd(2, "0");
36+
37+
return (${pounds}.${pence}`);
38+
}
39+
40+
console.log(toPounds("399p"));
41+
console.log(toPounds("5p"));
42+
console.log(toPounds("abc"));
43+

0 commit comments

Comments
 (0)