Elffuss BraidHub

kikocis/continue public

main · 9.2 KiBRawPermalink
1// Refactored shopping cart implementation following SOLID principles
2
3// Types and interfaces
4interface Product {
5 id: number;
6 name: string;
7 price: number;
8 stock: number;
9 category: string;
10}
11
12interface CartItem {
13 productId: number;
14 quantity: number;
15 price: number;
16}
17
18interface Discount {
19 percentage: number;
20 minPurchase: number;
21 category?: string;
22}
23
24interface UserInfo {
25 name: string;
26 email: string;
27 address?: Address;
28}
29
30interface Address {
31 street: string;
32 city: string;
33 zipCode: string;
34 country: string;
35}
36
37interface CartSummary {
38 items: CartItem[];
39 total: number;
40 discountCode: string | null;
41 user: UserInfo | null;
42}
43
44// Product catalog
45const PRODUCTS: Record<number, Product> = {
46 1: {
47 id: 1,
48 name: "Laptop",
49 price: 999.99,
50 stock: 10,
51 category: "electronics",
52 },
53 2: {
54 id: 2,
55 name: "Smartphone",
56 price: 699.99,
57 stock: 15,
58 category: "electronics",
59 },
60 3: {
61 id: 3,
62 name: "Headphones",
63 price: 149.99,
64 stock: 20,
65 category: "electronics",
66 },
67 4: { id: 4, name: "Desk", price: 249.99, stock: 5, category: "furniture" },
68 5: { id: 5, name: "Chair", price: 179.99, stock: 8, category: "furniture" },
69};
70
71// Discount codes
72const DISCOUNT_CODES: Record<string, Discount> = {
73 SAVE10: { percentage: 10, minPurchase: 0 },
74 SAVE20: { percentage: 20, minPurchase: 500 },
75 FURNITURE15: { percentage: 15, minPurchase: 0, category: "furniture" },
76};
77
78// Shopping cart class that follows Single Responsibility Principle
79class ShoppingCart {
80 private items: CartItem[] = [];
81 private total: number = 0;
82 private discountCode: string | null = null;
83 private userInfo: UserInfo | null = null;
84
85 // Add product to cart
86 public addToCart(productId: number, quantity: number = 1): boolean {
87 // Check if product exists
88 if (!PRODUCTS[productId]) {
89 console.error("Product not found!");
90 return false;
91 }
92
93 // Check if enough stock
94 if (PRODUCTS[productId].stock < quantity) {
95 console.error("Not enough stock!");
96 return false;
97 }
98
99 // Check if product already in cart
100 const existingItemIndex = this.findItemIndex(productId);
101
102 if (existingItemIndex !== -1) {
103 // Update quantity if product already in cart
104 this.items[existingItemIndex].quantity += quantity;
105 } else {
106 // Add new item if not already in cart
107 this.items.push({
108 productId,
109 quantity,
110 price: PRODUCTS[productId].price,
111 });
112 }
113
114 // Update stock
115 PRODUCTS[productId].stock -= quantity;
116
117 // Recalculate cart total
118 this.calculateCartTotal();
119
120 return true;
121 }
122
123 // Remove product from cart
124 public removeFromCart(productId: number, quantity: number = 1): boolean {
125 const itemIndex = this.findItemIndex(productId);
126
127 if (itemIndex === -1) {
128 console.error("Product not in cart!");
129 return false;
130 }
131
132 const item = this.items[itemIndex];
133
134 // Determine quantity to remove
135 const qtyToRemove = Math.min(item.quantity, quantity);
136
137 // Return stock
138 PRODUCTS[productId].stock += qtyToRemove;
139
140 // Update cart item
141 item.quantity -= qtyToRemove;
142
143 // Remove item if quantity is 0
144 if (item.quantity === 0) {
145 this.items.splice(itemIndex, 1);
146 }
147
148 // Recalculate cart total
149 this.calculateCartTotal();
150
151 return true;
152 }
153
154 // Calculate cart total
155 public calculateCartTotal(): number {
156 let total = this.calculateSubtotal();
157
158 // Apply discount if any
159 if (this.discountCode) {
160 total = this.applyDiscountToTotal(total);
161 }
162
163 this.total = total;
164 return this.total;
165 }
166
167 // Calculate subtotal without discounts
168 private calculateSubtotal(): number {
169 return this.items.reduce(
170 (sum, item) => sum + item.price * item.quantity,
171 0,
172 );
173 }
174
175 // Apply discount to total
176 private applyDiscountToTotal(total: number): number {
177 if (!this.discountCode) return total;
178
179 const discount = DISCOUNT_CODES[this.discountCode];
180
181 // Check if discount applies to specific category
182 if (discount.category) {
183 return this.applyCategoryDiscount(total, discount);
184 } else {
185 // Apply discount to entire cart
186 const discountAmount = total * (discount.percentage / 100);
187 return total - discountAmount;
188 }
189 }
190
191 // Apply category-specific discount
192 private applyCategoryDiscount(total: number, discount: Discount): number {
193 let categoryTotal = 0;
194
195 for (const item of this.items) {
196 if (PRODUCTS[item.productId].category === discount.category) {
197 categoryTotal += item.price * item.quantity;
198 }
199 }
200
201 // Apply discount to category total
202 const discountAmount = categoryTotal * (discount.percentage / 100);
203 return total - discountAmount;
204 }
205
206 // Apply discount code
207 public applyDiscountCode(code: string): boolean {
208 // Check if discount code exists
209 if (!DISCOUNT_CODES[code]) {
210 console.error("Invalid discount code!");
211 return false;
212 }
213
214 const discount = DISCOUNT_CODES[code];
215
216 // Check minimum purchase requirement
217 if (this.total < discount.minPurchase) {
218 console.error(
219 `Minimum purchase of $${discount.minPurchase} required for this code!`,
220 );
221 return false;
222 }
223
224 // Apply discount code
225 this.discountCode = code;
226
227 // Recalculate total
228 this.calculateCartTotal();
229
230 return true;
231 }
232
233 // Set user information
234 public setUserInfo(name: string, email: string, address?: Address): boolean {
235 this.userInfo = { name, email, address };
236 return true;
237 }
238
239 // Find item index in cart
240 private findItemIndex(productId: number): number {
241 return this.items.findIndex((item) => item.productId === productId);
242 }
243
244 // Checkout
245 public checkout(): boolean {
246 // Validate cart
247 if (this.items.length === 0) {
248 console.error("Cart is empty!");
249 return false;
250 }
251
252 // Validate user info
253 if (!this.userInfo || !this.userInfo.name || !this.userInfo.email) {
254 console.error("User information incomplete!");
255 return false;
256 }
257
258 // Process payment (simplified)
259 console.log("Processing payment for $" + this.total);
260 console.log("Items:", this.items);
261 console.log("User:", this.userInfo);
262
263 // Clear cart after successful checkout
264 this.clearCart();
265
266 return true;
267 }
268
269 // Clear cart
270 private clearCart(): void {
271 this.items = [];
272 this.total = 0;
273 this.discountCode = null;
274 }
275
276 // Get cart summary
277 public getCartSummary(): CartSummary {
278 return {
279 items: [...this.items], // Return a copy to prevent direct mutation
280 total: this.total,
281 discountCode: this.discountCode,
282 user: this.userInfo,
283 };
284 }
285}
286
287// Create cart instance
288const cart = new ShoppingCart();
289
290// Example usage
291cart.addToCart(1, 2); // Add 2 laptops
292cart.addToCart(3, 1); // Add 1 headphones
293cart.applyDiscountCode("SAVE10");
294cart.setUserInfo("John Doe", "john@example.com", {
295 street: "123 Main St",
296 city: "Anytown",
297 zipCode: "12345",
298 country: "USA",
299});
300
301console.log(cart.getCartSummary());
302
303// Export for module usage
304export {
305 Address,
306 cart,
307 CartItem,
308 CartSummary,
309 Discount,
310 DISCOUNT_CODES,
311 Product,
312 PRODUCTS,
313 ShoppingCart,
314 UserInfo,
315};
316
317/*
318Code Smells in the Original File
319Global State: The code uses global variables for cart state, making it difficult to track changes and prone to side effects.
320
321Lack of Encapsulation: Data and functions are not properly encapsulated, allowing direct manipulation of state from anywhere.
322
323No Type Definitions: Lack of proper TypeScript interfaces for the domain entities.
324
325Procedural Code: Functions operating on global state rather than object-oriented approach.
326
327Poor Data Structure Access: Using for loops with indexes instead of more expressive array methods.
328
329Mixed Responsibilities: Functions are handling multiple concerns (validation, business logic, data modification).
330
331Duplicated Logic: Same validation and calculation logic repeated in multiple places.
332
333No Clear Separation of Concerns: Business logic mixed with presentation logic (console logs).
334
335No Protection Against Direct Mutation: The cart data can be modified directly.
336
337
338Improvements Made
339
340Created a Class-Based Design: Encapsulated cart functionality in a ShoppingCart class
341
342Added Strong Typing: Defined interfaces for all domain entities (Product, CartItem, Discount, UserInfo, Address, CartSummary)
343
344Single Responsibility Principle: Separated methods for different concerns (e.g., split discount calculation into multiple methods)
345
346Encapsulation: Made cart items and state private, only accessible through methods
347
348Immutability: Return copies of data structures to prevent external modification
349
350Modern JavaScript/TypeScript Patterns:
351
352Used array methods like reduce, findIndex instead of for loops
353Used parameter defaults, array spread operators
354
355
356Better Method Organization:
357
358Split large methods into smaller, focused ones
359Created private helper methods for internal operations
360
361
362Improved Validation: Centralized validation logic in appropriate methods
363
364Better Error Handling: Consistent error reporting approach
365
366Code Reusability: Extracted reusable logic into dedicated methods
367
368Defensive Programming: Added checks to prevent invalid operations
369
370Cleaner API Design: Created a clear public interface for the cart functionality
371*/