设计思路
- 数据结构:使用数组存储购物车中的商品,每个商品为一个对象,包含商品ID、名称、价格、数量等信息。同时使用一个对象存储折扣规则。
- 核心函数:
addItem
:向购物车中添加商品。
removeItem
:从购物车中移除商品。
calculateTotal
:计算购物车商品总价。
applyDiscount
:应用折扣计算最终价格。
- 用户操作处理:通过调用上述核心函数实现不同用户操作。
关键代码示例
// 数据结构
const cart = [];
const discountRules = {
percentage: 0.1,
minAmount: 100
};
// 添加商品函数
const addItem = (product, quantity = 1) => {
const existingItem = cart.find(item => item.id === product.id);
if (existingItem) {
existingItem.quantity += quantity;
} else {
cart.push({...product, quantity });
}
return cart;
};
// 移除商品函数
const removeItem = (productId) => {
return cart.filter(item => item.id!== productId);
};
// 计算总价函数
const calculateTotal = () => {
return cart.reduce((total, item) => total + item.price * item.quantity, 0);
};
// 应用折扣函数
const applyDiscount = (total) => {
if (total >= discountRules.minAmount) {
return total * (1 - discountRules.percentage);
}
return total;
};
函数式设计相较于传统面向对象设计的优势
- 可维护性:函数式编程中函数无副作用,更容易理解和调试,当某个功能出现问题时,更容易定位。
- 可测试性:纯函数使得测试更加简单,只需要关注输入和输出,不需要考虑对象状态等复杂因素。
- 复用性:函数式编程的函数专注于单一功能,更易于复用,例如
calculateTotal
函数可以在不同场景下计算总价。
- 并行处理:函数式编程更适合并行处理,因为函数无副作用,不会相互干扰,这在电商高并发场景下有潜在优势。