// 纯函数示例
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
function calculateDiscount(price, discountPercent) {
return price * (1 - discountPercent / 100);
}
// 非纯函数示例
let total = 0;
function addToTotal(amount) {
total += amount; // 修改外部状态
return total;
}
function getRandomNumber() {
return Math.random(); // 依赖外部随机数生成器
}
function updateUser(user, newName) {
user.name = newName; // 直接修改传入的对象
return user;
}
// 纯函数版本
function createUpdatedUser(user, newName) {
return {
...user,
name: newName
};
}