Skip to content

Commit 6c1636f

Browse files
committed
In 3-mandatory-implement/3-to-pounds.js, created a reusable function toPounds with input condition checks
1 parent a505558 commit 6c1636f

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

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

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,64 @@
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+
/* Code from Sprint-1 below for reference
9+
const penceString = "399p";
10+
11+
const penceStringWithoutTrailingP = penceString.substring(
12+
0,
13+
penceString.length - 1
14+
);
15+
16+
const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0");
17+
const pounds = paddedPenceNumberString.substring(
18+
0,
19+
paddedPenceNumberString.length - 2
20+
);
21+
22+
const pence = paddedPenceNumberString
23+
.substring(paddedPenceNumberString.length - 2)
24+
.padEnd(2, "0");
25+
26+
console.log(`£${pounds}.${pence}`);
27+
*/
28+
29+
function toPounds(penceString) {
30+
if (typeof penceString !== "string" || !penceString.endsWith("p")) {
31+
console.log("Invalid input, please provide a penceString ending with 'p'");
32+
return "Invalid input, please provide a penceString ending with 'p'";
33+
}
34+
35+
const penceStringWithoutTrailingP = penceString.substring(
36+
0,
37+
penceString.length - 1
38+
);
39+
40+
if (Number.isNaN(Number(penceStringWithoutTrailingP))) {
41+
console.log("Invalid input, please provide a numeric penceString");
42+
return "Invalid input, please provide a numeric penceString";
43+
}
44+
45+
const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0");
46+
const pounds = paddedPenceNumberString.substring(
47+
0,
48+
paddedPenceNumberString.length - 2
49+
);
50+
51+
const pence = paddedPenceNumberString
52+
.substring(paddedPenceNumberString.length - 2)
53+
.padEnd(2, "0");
54+
55+
console.log(${pounds}.${pence}`);
56+
return ${pounds}.${pence}`;
57+
}
58+
59+
toPounds("399p");
60+
toPounds("5p");
61+
toPounds("89p");
62+
toPounds("1234p");
63+
toPounds("0p");
64+
toPounds("70000p");
65+
toPounds("abcp");
66+
toPounds(500);
67+
toPounds("abc");

0 commit comments

Comments
 (0)