Elffuss BraidHub

kikocis/continue public

main · 2.1 KiBRawPermalink
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 */
7interface 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 */
19function 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
34const 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
41const finalPrice = calculateTotalPrice(cart, 10);
42console.log(`Final price: $${finalPrice}`);
43
44// Export function
45export default calculateTotalPrice;
46
47/*
48Single Responsibility Principle:
49
50The function now has a clearer, more descriptive name: calculateTotalPrice instead of calc_price
51Used proper camelCase naming convention for JavaScript/TypeScript functions
52
53
54Type Safety:
55
56Created a proper PricedItem interface instead of using any[]
57Added proper type annotations throughout the code
58
59
60Code Quality Improvements:
61
62Replaced the for loop with a more functional reduce() approach
63Used const instead of let where variables aren't reassigned
64Used default parameter syntax instead of conditional checking
65Improved variable naming for clarity
66Added JSDoc comments for better documentation
67Used template literals instead of string concatenation
68
69
70Fixed Potential Issues:
71
72Replaced loose inequality check (!=) with default parameter
73Changed var to const in the loop to avoid scope issues
74Made intermediate calculations more explicit with named variables
75
76
77Maintainability:
78
79Added proper documentation with JSDoc comments
80Used more explicit and descriptive variable names
81*/