-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_model.h
110 lines (81 loc) · 1.72 KB
/
data_model.h
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
//Product, Item, Cart
#include<string>
#include<unordered_map>
using namespace std;
//Forward Declaration
class Item;
class Cart;
class Product{
int id;
string name;
int price;
public:
Product(){
}
Product(int u_id, string name,int price){
id = u_id;
this->name = name;
this->price = price;
}
string getDisplayName(){
return name + " : Rs " + to_string(price) + "\n";
}
string getShortName(){
return name.substr(0,1);
}
friend class Item;
friend class Cart;
};
class Item{
Product product;
int quantity;
public:
//Constructor using a Init List
Item(){}
Item(Product p, int q):product(p), quantity(q){}
int getItemPrice(){
return quantity * product.price;
}
string getItemInfo(){
return to_string(quantity) + " x " + product.name + " Rs. " + to_string(quantity * product.price) + "\n";
}
friend class Cart;
};
class Cart{
unordered_map<int,Item> items;
public:
void addProduct(Product product){
if(items.count(product.id)==0){
Item newItem(product,1);
items[product.id] = newItem;
}
else{
items[product.id].quantity += 1;
}
}
int getTotal(){
//Todo
int total = 0;
for(auto itemPair : items){
auto item = itemPair.second;
total += item.getItemPrice();
}
return total;
}
string viewCart(){
if(items.empty()){
return "Cart is empty";
}
string itemizedList;
int cart_total = getTotal();
for(auto itemPair : items){
auto item = itemPair.second;
itemizedList.append(item.getItemInfo());
}
return itemizedList + "\n Total Amount : Rs. " + to_string(cart_total) + '\n';
}
//later on
bool isEmpty(){
return items.empty();
}
};