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
68 lines (55 loc) · 2.02 KB
/
ex6-totalCost.js
File metadata and controls
68 lines (55 loc) · 2.02 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
64
65
66
67
68
/*------------------------------------------------------------------------------
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.
-----------------------------------------------------------------------------*/
// Create an object with 5 grocery items
const cartForParty = {
beers: 5.25,
chips: 1.5,
soda: 2.0,
cookies: 3.75,
cheese: 4.25,
};
// Function to calculate total price of items in an object
function calculateTotalPrice(cart) {
let total = 0;
// Loop through object values and sum them
for (const item in cart) {
if (cart.hasOwnProperty(item)) {
total += cart[item];
}
}
// Return formatted total
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);
}
function test2() {
console.log('\nTest 2: return correct output when passed cartForParty');
const expected = 'Total: €16.75';
const actual = calculateTotalPrice(cartForParty);
console.assert(
actual === expected,
`Expected "${expected}", but got "${actual}"`
);
}
function test() {
test1();
test2();
}
test();