forked from HackYourFuture/Assignments
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathex6-totalCost.js
More file actions
63 lines (52 loc) · 2.12 KB
/
ex6-totalCost.js
File metadata and controls
63 lines (52 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*------------------------------------------------------------------------------
Full description at: https://github.com/HackYourFuture/Assignments/tree/main/1-JavaScript/Week3#exercise-6-total-cost-is
You want to buy a couple of things from the supermarket to prepare for a party.
After scanning all the items the cashier wants to give you the total price, but
the machine is broken! Let's write her a function that does it for her
instead!
1. Create an object named `cartForParty` with five properties. Each property
should be a grocery item (like `beers` or `chips`) and hold a number value
(like `1.75` or `0.99`).
2. Complete the function called `calculateTotalPrice`.
- It takes one parameter: an object that contains properties that only contain
number values.
- Loop through the object and add all the number values together.
- Return a string: "Total: €`amount`".
3. Complete the unit test functions and verify that all is working as expected.
-----------------------------------------------------------------------------*/
const cartForParty = {
vine: 5.75,
water: 0.73,
juice: 1.26,
croissant: 3.98,
coffe: 2.33
};
function calculateTotalPrice(object) {
let total = 0;
for (let item in object) {
total += object[item];
}
return `Total: €${total.toFixed(2)}`;
}
// Additional challenge: These lines go through all the keys in the object and add their values to total.
// Another way is to use
//. function calculateTotalPrice(object) {
// let total = Object.values(object).reduce((sum, val) => sum + val, 0);
// return `Total: €${total.toFixed(2)}`;
// }
// ! Test functions (plain vanilla JavaScript)
function test1() {
console.log('\nTest 1: calculateTotalPrice should take one parameter');
console.assert(calculateTotalPrice.length === 1, "Should take one parameter");
}
function test2() {
console.log('\nTest 2: return correct output when passed cartForParty');
const expected = "Total: €14.05";
const actual = calculateTotalPrice(cartForParty);
console.assert(actual === expected, `Expected "${expected}", got "${actual}"`);
}
function test() {
test1();
test2();
}
test();