Utility Class Methods in TypeScript
This challenge focuses on implementing utility methods within a TypeScript class. Utility methods are helper functions that operate on the class's data or provide common functionality, enhancing code reusability and readability. Successfully completing this challenge demonstrates understanding of TypeScript classes, methods, and object manipulation.
Problem Description
You are tasked with creating a ShoppingCart class in TypeScript. This class will manage a list of items and provide utility methods to calculate the total price, apply discounts, and format the cart contents for display. The class should be well-structured, maintainable, and adhere to TypeScript best practices.
What needs to be achieved:
- Create a
ShoppingCartclass with anitemsproperty (an array of objects). Each item object should havename(string),price(number), andquantity(number) properties. - Implement a
addItemmethod to add an item to the cart. - Implement a
removeItemmethod to remove an item from the cart by name. - Implement a
calculateTotalPricemethod that calculates the total price of all items in the cart. - Implement a
applyDiscountmethod that applies a percentage-based discount to the total price. - Implement a
formatCartmethod that returns a formatted string representation of the cart contents, suitable for display.
Key Requirements:
- The
itemsarray should be initialized as an empty array. addItemshould handle cases where an item already exists in the cart (increment the quantity instead of adding a duplicate).removeItemshould handle cases where the item doesn't exist in the cart gracefully (e.g., no error, or a message).calculateTotalPriceshould return 0 if the cart is empty.applyDiscountshould handle invalid discount percentages (e.g., negative or greater than 100) by returning an error message.formatCartshould display each item's name, quantity, and price, and the total price.
Expected Behavior:
The class should behave as described above, providing accurate calculations and formatted output. The code should be clean, well-documented, and easy to understand.
Edge Cases to Consider:
- Empty cart
- Item already exists in the cart
- Item not found in the cart
- Invalid discount percentage (negative, zero, or greater than 100)
- Zero or negative price/quantity values (handle appropriately - perhaps throw an error or treat as invalid)
Examples
Example 1:
Input:
cart.addItem({ name: "Apple", price: 1.00, quantity: 2 });
cart.addItem({ name: "Banana", price: 0.50, quantity: 3 });
Output:
"Cart Contents:\nApple: 2 x $1.00 = $2.00\nBanana: 3 x $0.50 = $1.50\nTotal: $3.50"
Explanation: Two items are added to the cart, and the formatCart method displays their details and the total price.
Example 2:
Input:
cart.addItem({ name: "Apple", price: 1.00, quantity: 2 });
cart.applyDiscount(10);
Output:
"Discount applied: 10%\nNew Total: $3.15"
Explanation: A 10% discount is applied to the total price, and the updated total is displayed.
Example 3:
Input:
cart.removeItem("Orange");
Output:
"Item 'Orange' not found in cart."
Explanation: Attempting to remove an item that doesn't exist results in a message indicating that the item was not found.
Constraints
- The
priceandquantityproperties of items must be non-negative numbers. - The discount percentage must be a number between 0 and 100 (inclusive).
- The
formatCartmethod should return a string. - The
calculateTotalPricemethod should return a number. - The
applyDiscountmethod should return a string indicating the discount applied and the new total, or an error message if the discount is invalid.
Notes
- Consider using TypeScript's type annotations to ensure type safety.
- Think about how to handle errors and invalid input gracefully.
- Focus on writing clean, readable, and maintainable code.
- You can use template literals for string formatting in the
formatCartmethod. - Error handling can be implemented using try-catch blocks or by returning specific error messages.