-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathshoppingCartSolution.js
51 lines (47 loc) · 1.59 KB
/
shoppingCartSolution.js
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
function makeCart(shopper) {
return {
shopper, // shorthand for shopper: shopper,
items: [],
addItem(itemName, price) { // shorthand for addItem: function(itemName, price)
this.items.push({itemName, price});
return `${itemName} added to the cart`
},
removeItem(itemName) {
const indexToRemove = this.items.findIndex(element => element.itemName === itemName);
if (indexToRemove >= 0) {
const before = this.items.slice(0, indexToRemove);
const after = this.items.slice(indexToRemove + 1);
this.items = [...before, ...after];
}
/* Or, implemented using splice and forEach
this.items.forEach((item, i) => {
if (item.itemName === itemName) {
this.items.splice(i, 1);
}
});
*/
},
getTotal() {
return this.items.reduce((total, item) => total + item.price, 0)
},
getItemList() {
return this.items.map(element => element.itemName)
},
removeMostExpensiveItem() {
this.items.sort((a, b) => a.price < b.price ? -1 : 1)
this.items.pop();
}
}
}
const cart = makeCart("ben");
console.log(cart);
cart.addItem("apple", 1);
cart.addItem("banana", 0.5);
cart.addItem("cherries", 2.5);
cart.addItem("dates", 3);
cart.addItem("eggplant", 1.5);
console.log(cart.items);
console.log(cart.getTotal());
cart.removeItem("dates")
cart.removeMostExpensiveItem()
console.log(cart);