从函数修改和返回新对象的最佳做法是什么?
我写了下面的函数:
export const addItemToCart = (currentCart, item) => {
const { name, ...otherProps } = item;
//if item exist in the cart
if (currentCart[name]) {
currentCart[name]["quantity"]++;
return currentCart;
}
//if the item does not exist
else
{
currentCart[name] = { ...otherProps };
currentCart[name]["quantity"] = 1;
return currentCart;
}
// the function must return a new modified object on each call
};
显然,硬编码属性“数量”和返回语句肯定可以改进。
如何改进此函数以使其更具可读性?
最佳答案
更多的“可读性”是非常基于意见的,无论哪种方式,你都可以尝试这样的事情:
const currentCart = {
hello: {
quantity: 1
}
};
const addItemToCart = (currentCart, item) => {
const { name } = item;
// Short circuit + return the last value
const quantityPrev = currentCart[name] && currentCart[name].quantity;
// Or operator on boolean expression
const quantity = 1 + (quantityPrev || 0);
// Destructing for shallow copy, dynamic key assign
return { ...currentCart, [name]: { quantity } };
};
console.log(addItemToCart(currentCart, { name: 'hello' }));
console.log(addItemToCart(currentCart, { name: 'blazer' }));
关于javascript - 从函数返回修改后的新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57956617/