-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
138 lines (112 loc) · 2.75 KB
/
app.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
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
const products = [{
id: 1,
name: 'iPhone 12',
price: 30000000,
image: './images/iphone-12.png',
},
{
id: 2,
name: 'AirPods',
price: 6000000,
image: './images/airpods.png',
},
]
let cart = {
items: [],
total: 0,
}
const renderProducts = () => {
const productDiv = document.querySelector('.products')
productDiv.innerHTML = ''
products.forEach((item, index) => {
productDiv.innerHTML += `
<div class="product">
<div class="product__image">
<img src=${item.image} />
</div>
<h2 class="product__title">${item.name}</h2>
<h3 class="product__price">${item.price} تومان</h3>
<button class="add-to-cart" onclick="addToCart(${index})">افزودن به سبد خرید</button>
</div>
`
})
}
const renderCartItems = () => {
const cartDiv = document.querySelector('.cart__items')
cartDiv.innerHTML = ''
const totalPriceEl = document.querySelector('.cart__total-price')
let totalPrice = 0
if (cart.items.length === 0) {
cartDiv.innerHTML = 'محصولی در سبد خرید وجود ندارد'
}
cart.items.forEach((item) => {
totalPrice += item.total
cartDiv.innerHTML += `
<div class="cart__item">
<div class="col-md-4">
<button class="cart__item-remove" onclick="removeFromCart('${item.name}')">حذف</button>
</div>
<div class="col-md-4">
<div class="qty">${item.qty}</div>
</div>
<div class="col-md-4">
<h3 class="cart__item-title">${item.name}</h3>
</div>
</div>
`
})
totalPriceEl.innerHTML = `مجموع: ${totalPrice} تومان`
}
const addToCart = (productIndex) => {
const product = products[productIndex]
let existingProduct = false
let newCartItems = cart.items.reduce((state, item) => {
if (item.name === product.name) {
existingProduct = true
const newItem = {
...item,
qty: item.qty + 1,
total: (item.qty + 1) * item.price,
}
return [...state, newItem]
}
return [...state, item]
}, [])
if (!existingProduct) {
newCartItems.push({
...product,
qty: 1,
total: product.price,
})
}
cart = {
...cart,
items: newCartItems,
}
renderCartItems()
}
const removeFromCart = (productName) => {
let newCartItems = cart.items.reduce((state, item) => {
if (item.name === productName) {
const newItem = {
...item,
qty: item.qty - 1,
total: (item.qty - 1) * item.price,
}
if (newItem.qty > 0) {
return [...state, newItem]
} else {
return state
}
}
return [...state, item]
}, [])
cart = {
...cart,
items: newCartItems,
}
renderCartItems()
}
renderProducts()
renderCartItems()
// Developed By Mohammad Kiaei