Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor evolve and evolveWithMetadata to avoid code duplication and a potential bug for amounts #196

Open
shraddha38 opened this issue Feb 18, 2025 · 0 comments

Comments

@shraddha38
Copy link

Summary:

The evolve and evolveWithMetadata functions in ShoppingCart have some code duplication and lack safety for new event types.

Suggested Improvements

  1. Removing duplication - Reduce duplication in event handling logic and ensure safety by adding a default case in switch statements

Same logic is used in evolve and evolveMetatadata fn, so we can extract it as following -

const updateCart = (state: ShoppingCart, productItem: PricedProductItem): ShoppingCart => ({
  productItems: [...state.productItems, productItem],
  totalAmount: state.totalAmount + productItem.price * productItem.quantity,
});
  1. Bug- Prevent discounts from causing negative amounts

Current

 case 'DiscountApplied':
      return {
        ...state,
        totalAmount: state.totalAmount * (1 - data.percent / 100),
      };

Suggestion

 case 'DiscountApplied':
      return {
        ...state,
        totalAmount: Math.max(state.totalAmount * (1 - data.percent / 100), 0),
      };

Next Steps

  1. Need review from maintainers on this issue.
  2. After that I can create a Pr for the changes.
@shraddha38 shraddha38 changed the title Refactor evolve and evolveWithMetadata to avoid code deduplication and a potential bug for amounts Refactor evolve and evolveWithMetadata to avoid code duplication and a potential bug for amounts Feb 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant