从函数修改并返回新对象的最佳实践是什么?

我写了以下函数:

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
};


显然,硬编码的属性“ quantity”和return语句肯定可以得到改善。

如何改善此功能以使其更具可读性?

最佳答案

无论哪种方式,更“可读”的内容都是基于意见的,您可以尝试执行以下操作:



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' }));

09-25 19:04