| 1 | // A simple utility function with minor issues |
| 2 | // Difficulty: 1 - Easy fixes needed |
| 3 | |
| 4 | // Function to calculate total price with discount |
| 5 | function calc_price(items: any[], discountPercentage?: number) { |
| 6 | // Calculate total price |
| 7 | let total = 0; |
| 8 | for (var i = 0; i < items.length; i++) { |
| 9 | total = total + items[i].price; |
| 10 | } |
| 11 | |
| 12 | // Apply discount |
| 13 | if (discountPercentage != undefined) { |
| 14 | total = total - (total * discountPercentage) / 100; |
| 15 | } |
| 16 | |
| 17 | return total; |
| 18 | } |
| 19 | |
| 20 | // Example usage |
| 21 | const cart = [ |
| 22 | { name: "Shirt", price: 25 }, |
| 23 | { name: "Pants", price: 50 }, |
| 24 | { name: "Shoes", price: 100 }, |
| 25 | ]; |
| 26 | |
| 27 | // Calculate price with 10% discount |
| 28 | const finalPrice = calc_price(cart, 10); |
| 29 | console.log("Final price: $" + finalPrice); |
| 30 | |
| 31 | // Export function |
| 32 | export default calc_price; |