Skip to content

Commit f204ada

Browse files
authored
Fix totalTill implementation and add test case
Fixed the totalTill function implementation to correctly calculate the total amount in pounds from the till object. Added a test case to verify the functionality.
1 parent 3dfb2a8 commit f204ada

1 file changed

Lines changed: 35 additions & 3 deletions

File tree

‎Sprint-2/stretch/till.js‎

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,41 @@ const till = {
2323
const totalAmount = totalTill(till);
2424

2525
// a) What is the target output when totalTill is called with the till object
26-
26+
"£4.40"
2727
// b) Why do we need to use Object.entries inside the for...of loop in this function?
28-
28+
We need it because plain objects are not directly iterable using a for...of loop in JavaScript. Using Object.entries allows us to loop through the entries
2929
// c) What does coin * quantity evaluate to inside the for...of loop?
30-
30+
coin * quantity evaluates to NaN (Not-a-Number).
3131
// d) Write a test for this function to check it works and then fix the implementation of totalTill
32+
function totalTill(till) {
33+
let totalPence = 0;
34+
35+
for (const [coin, quantity] of Object.entries(till)) {
36+
// Parse the numeric pence value from strings like "50p" -> 50
37+
const penceValue = parseInt(coin, 10);
38+
39+
if (!isNaN(penceValue)) {
40+
totalPence += penceValue * quantity;
41+
}
42+
}
43+
44+
// Convert pence to pounds and format to 2 decimal places
45+
const pounds = (totalPence / 100).toFixed(2);
46+
return `£${pounds}`;
47+
}
48+
49+
module.exports = totalTill;
50+
51+
const totalTill = require("./totalTill.js");
52+
53+
describe("totalTill", () => {
54+
test("calculates the correct total for a given till object", () => {
55+
const till = {
56+
"1p": 10,
57+
"5p": 6,
58+
"50p": 4,
59+
"20p": 10,
60+
};
61+
expect(totalTill(till)).toBe("£4.40");
62+
});
63+
});

0 commit comments

Comments
 (0)