webupdatev1
This commit is contained in:
@@ -61,7 +61,7 @@
|
||||
|
||||
// Cart methods
|
||||
addToCart(product, quantity = 1) {
|
||||
const existing = this.state.cart.find((item) => item.id === product.id);
|
||||
const existing = this._findById(this.state.cart, product.id);
|
||||
|
||||
if (existing) {
|
||||
existing.quantity += quantity;
|
||||
@@ -73,27 +73,26 @@
|
||||
});
|
||||
}
|
||||
|
||||
this.saveToStorage();
|
||||
this.emit("cartUpdated", this.state.cart);
|
||||
this._updateState("cart");
|
||||
return this.state.cart;
|
||||
}
|
||||
|
||||
removeFromCart(productId) {
|
||||
this.state.cart = this.state.cart.filter((item) => item.id !== productId);
|
||||
this.saveToStorage();
|
||||
this.emit("cartUpdated", this.state.cart);
|
||||
this.state.cart = this.state.cart.filter(
|
||||
(item) => String(item.id) !== String(productId)
|
||||
);
|
||||
this._updateState("cart");
|
||||
return this.state.cart;
|
||||
}
|
||||
|
||||
updateCartQuantity(productId, quantity) {
|
||||
const item = this.state.cart.find((item) => item.id === productId);
|
||||
const item = this._findById(this.state.cart, productId);
|
||||
if (item) {
|
||||
item.quantity = Math.max(0, quantity);
|
||||
if (item.quantity === 0) {
|
||||
return this.removeFromCart(productId);
|
||||
}
|
||||
this.saveToStorage();
|
||||
this.emit("cartUpdated", this.state.cart);
|
||||
this._updateState("cart");
|
||||
}
|
||||
return this.state.cart;
|
||||
}
|
||||
@@ -103,20 +102,16 @@
|
||||
}
|
||||
|
||||
getCartTotal() {
|
||||
return this.state.cart.reduce(
|
||||
(sum, item) => sum + item.price * item.quantity,
|
||||
0
|
||||
);
|
||||
return this._calculateTotal(this.state.cart);
|
||||
}
|
||||
|
||||
getCartCount() {
|
||||
return this.state.cart.reduce((sum, item) => sum + item.quantity, 0);
|
||||
return this._calculateCount(this.state.cart);
|
||||
}
|
||||
|
||||
clearCart() {
|
||||
this.state.cart = [];
|
||||
this.saveToStorage();
|
||||
this.emit("cartUpdated", this.state.cart);
|
||||
this._updateState("cart");
|
||||
}
|
||||
|
||||
// Wishlist methods
|
||||
@@ -179,6 +174,31 @@
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Helper methods
|
||||
_findById(collection, id) {
|
||||
return collection.find((item) => String(item.id) === String(id));
|
||||
}
|
||||
|
||||
_updateState(type) {
|
||||
this.saveToStorage();
|
||||
this.emit(`${type}Updated`, this.state[type]);
|
||||
}
|
||||
|
||||
_calculateTotal(items) {
|
||||
return items.reduce((sum, item) => {
|
||||
const price = parseFloat(item.price) || 0;
|
||||
const quantity = parseInt(item.quantity) || 0;
|
||||
return sum + price * quantity;
|
||||
}, 0);
|
||||
}
|
||||
|
||||
_calculateCount(items) {
|
||||
return items.reduce((sum, item) => {
|
||||
const quantity = parseInt(item.quantity) || 0;
|
||||
return sum + quantity;
|
||||
}, 0);
|
||||
}
|
||||
}
|
||||
|
||||
// Create global instance
|
||||
|
||||
Reference in New Issue
Block a user