forked from HackYourFuture/Assignments
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathex4-shoppingCart.js
More file actions
79 lines (65 loc) · 2.51 KB
/
ex4-shoppingCart.js
File metadata and controls
79 lines (65 loc) · 2.51 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
69
70
71
72
73
74
75
76
77
78
79
/*------------------------------------------------------------------------------
Full description at: https://github.com/HackYourFuture/Assignments/tree/main/1-JavaScript/Week3#exercise-4-shopping-at-the-supermarket
Let's do some grocery shopping! We're going to get some things to cook dinner
with. However, you like to spend money and always buy too many things. So when
you have more than 3 items in your shopping cart the first item gets taken out.
1. Complete the function named `addToShoppingCart` as follows:
- It should take one argument: a grocery item (string)
- It should add the grocery item to the `shoppingCart` array. If the number of items is
more than three remove the first one in the array.
- It should return a string "You bought <list-of-items>!", where
<list-of-items>is a comma-separated list of items from the shopping cart
array.
2. Confirm that your code passes the unit tests.
-----------------------------------------------------------------------------*/
const shoppingCart = ['bananas', 'milk'];
function addToShoppingCart(item) {
if (item !== undefined) {
shoppingCart.push(item);
if (shoppingCart.length > 3) {
shoppingCart.shift();
}
}
return `You bought ${shoppingCart.join(', ')}!`;
}
// ! Test functions (plain vanilla JavaScript)
function test1() {
console.log(
'Test 1: addShoppingCart() called without an argument should leave the shopping cart unchanged'
);
const expected = 'You bought bananas, milk!';
const actual = addToShoppingCart();
console.assert(actual === expected);
}
function test2() {
console.log('Test 2: addShoppingCart() should take one parameter');
const expected = 1;
const actual = addToShoppingCart.length;
console.assert(actual === expected);
}
function test3() {
console.log('Test 3: `chocolate` should be added');
const expected = 'You bought bananas, milk, chocolate!';
const actual = addToShoppingCart('chocolate');
console.assert(actual === expected);
}
function test4() {
console.log('Test 4: `waffles` should be added and `bananas` removed');
const expected = 'You bought milk, chocolate, waffles!';
const actual = addToShoppingCart('waffles');
console.assert(actual === expected);
}
function test5() {
console.log('Test 5: `tea` should be added and `milk` removed');
const expected = 'You bought chocolate, waffles, tea!';
const actual = addToShoppingCart('tea');
console.assert(actual === expected);
}
function test() {
test1();
test2();
test3();
test4();
test5();
}
test();