Skip to content

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

Closed
@shraddha38

Description

@shraddha38

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions