|
5 | 5 | // Then it should return the total amount in pounds
|
6 | 6 |
|
7 | 7 | function totalTill(till) {
|
8 |
| - let total = 0; |
9 |
| - |
10 |
| - for (const [coin, quantity] of Object.entries(till)) { |
11 |
| - total += coin * quantity; |
| 8 | + if (till === 0) { |
| 9 | + return "0.00"; |
| 10 | + } else if (typeof till !== "object" || till === null || Array.isArray(till)) { |
| 11 | + throw new Error("The input is not a valid object"); |
| 12 | + } else { |
| 13 | + let total = 0; |
| 14 | + for (let [coin, quantity] of Object.entries(till)) { |
| 15 | + //transform till object into an array and |
| 16 | + // looping trough coin as a key and quantity as value |
| 17 | + |
| 18 | + if (coin.endsWith("p")) { |
| 19 | + coin = Number(coin.slice(0, -1)); // rid of "p" at the end of coin |
| 20 | + } else if (coin.startsWith("£")) { |
| 21 | + coin = Number(coin.slice(1)) * 100; // rid of "£" at the start of coin and transform pound to coin |
| 22 | + // by multiple by 100 |
| 23 | + } else { |
| 24 | + throw new Error("Invalid coin format"); |
| 25 | + } |
| 26 | + |
| 27 | + if (isNaN(coin)) { |
| 28 | + throw new Error("Invalid coin format"); |
| 29 | + } |
| 30 | + total += coin * quantity; // calculate total |
| 31 | + } |
| 32 | + return `£${(total / 100).toFixed(2)}`; // transform pence into pounds and round total to two decimal places |
12 | 33 | }
|
13 |
| - |
14 |
| - return `£${total / 100}`; |
15 | 34 | }
|
16 | 35 |
|
17 | 36 | const till = {
|
18 | 37 | "1p": 10,
|
19 | 38 | "5p": 6,
|
20 | 39 | "50p": 4,
|
21 |
| - "20p": 10, |
| 40 | + "20p": 0, |
22 | 41 | };
|
| 42 | + |
23 | 43 | const totalAmount = totalTill(till);
|
| 44 | +console.log(totalAmount); |
24 | 45 |
|
25 | 46 | // a) What is the target output when totalTill is called with the till object
|
| 47 | +//A total amount in pounds: e.g. £2.40, represented by pounds and coins with two decimal places. |
26 | 48 |
|
27 | 49 | // b) Why do we need to use Object.entries inside the for...of loop in this function?
|
| 50 | +// We need to use the Object.entries to transform the object into an array to get the ability |
| 51 | +// to pull keys and values at the same time from the till object to calculate the total. |
| 52 | +// e.g. 1p and 10 |
28 | 53 |
|
29 | 54 | // c) What does coin * quantity evaluate to inside the for...of loop?
|
| 55 | +// The coin and quantity evaluate to inside the for...of loop, the total pounds in pence |
| 56 | +// according to the type of coin in each array inside the Object.entries(till) array. |
30 | 57 |
|
31 | 58 | // d) Write a test for this function to check it works and then fix the implementation of totalTill
|
| 59 | + |
| 60 | +module.exports = totalTill; |
0 commit comments