| 1 | // A clean implementation of the price calculation utility |
| 2 | // Solution for: next-edit-1-1.ts |
| 3 | |
| 4 | /** |
| 5 | * Interface for a purchasable item |
| 6 | */ |
| 7 | interface PricedItem { |
| 8 | name: string; |
| 9 | price: number; |
| 10 | } |
| 11 | |
| 12 | /** |
| 13 | * Calculates the total price of items with an optional discount |
| 14 | * |
| 15 | * @param items - Array of priced items |
| 16 | * @param discountPercentage - Optional discount to apply (percentage) |
| 17 | * @returns The final price after discount |
| 18 | */ |
| 19 | function calculateTotalPrice( |
| 20 | items: PricedItem[], |
| 21 | discountPercentage = 0, |
| 22 | ): number { |
| 23 | // Calculate total price |
| 24 | const subtotal = items.reduce((total, item) => total + item.price, 0); |
| 25 | |
| 26 | // Apply discount |
| 27 | const discount = (subtotal * discountPercentage) / 100; |
| 28 | const finalPrice = subtotal - discount; |
| 29 | |
| 30 | return finalPrice; |
| 31 | } |
| 32 | |
| 33 | // Example usage |
| 34 | const cart: PricedItem[] = [ |
| 35 | { name: "Shirt", price: 25 }, |
| 36 | { name: "Pants", price: 50 }, |
| 37 | { name: "Shoes", price: 100 }, |
| 38 | ]; |
| 39 | |
| 40 | // Calculate price with 10% discount |
| 41 | const finalPrice = calculateTotalPrice(cart, 10); |
| 42 | console.log(`Final price: $${finalPrice}`); |
| 43 | |
| 44 | // Export function |
| 45 | export default calculateTotalPrice; |
| 46 | |
| 47 | /* |
| 48 | Single Responsibility Principle: |
| 49 | |
| 50 | The function now has a clearer, more descriptive name: calculateTotalPrice instead of calc_price |
| 51 | Used proper camelCase naming convention for JavaScript/TypeScript functions |
| 52 | |
| 53 | |
| 54 | Type Safety: |
| 55 | |
| 56 | Created a proper PricedItem interface instead of using any[] |
| 57 | Added proper type annotations throughout the code |
| 58 | |
| 59 | |
| 60 | Code Quality Improvements: |
| 61 | |
| 62 | Replaced the for loop with a more functional reduce() approach |
| 63 | Used const instead of let where variables aren't reassigned |
| 64 | Used default parameter syntax instead of conditional checking |
| 65 | Improved variable naming for clarity |
| 66 | Added JSDoc comments for better documentation |
| 67 | Used template literals instead of string concatenation |
| 68 | |
| 69 | |
| 70 | Fixed Potential Issues: |
| 71 | |
| 72 | Replaced loose inequality check (!=) with default parameter |
| 73 | Changed var to const in the loop to avoid scope issues |
| 74 | Made intermediate calculations more explicit with named variables |
| 75 | |
| 76 | |
| 77 | Maintainability: |
| 78 | |
| 79 | Added proper documentation with JSDoc comments |
| 80 | Used more explicit and descriptive variable names |
| 81 | */ |