Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[4팀 최하늘] [Chapter 2-2] 디자인 패턴과 함수형 프로그래밍 #27

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 9 additions & 7 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,16 @@ module.exports = {
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
'plugin:prettier/recommended',
'plugin:react/recommended',
'plugin:jsx-ally/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
ignorePatterns: ['dist', '.eslintrc.cjs', '**/node_modules/**'],
parser: '@typescript-eslint/parser',
plugins: ['react-refresh'],
plugins: ['react-refresh', 'react', 'prettier'],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
'prettier/prettier': 'error',
'no-empty-pattern': 'off',
},
}
};
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,7 @@ dist-ssr
*.njsproj
*.sln
*.sw?
*.yaml

package-lock.json
pnpm-lock.yaml
4 changes: 4 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
src/main.original.js
src/basic/**/__tests__/**
src/advanced/**/__tests__/**
*.md
12 changes: 12 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"semi": true,
"singleQuote": true,
"jsxSingleQuote": true,
"tabWidth": 2,
"trailingComma": "all",
"bracketSpacing": true,
"bracketSameLine": false,
"arrowParens": "always",
"printWidth": 100,
"endOfLine": "auto"
}
9 changes: 7 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,14 @@
"@typescript-eslint/parser": "^8.10.0",
"@vitejs/plugin-react-swc": "^3.7.1",
"@vitest/ui": "^2.1.3",
"eslint": "^9.12.0",
"eslint-plugin-react-hooks": "^5.0.0",
"eslint": "^9.18.0",
"eslint-plugin-jsx-a11y": "^6.10.2",
"eslint-plugin-prettier": "^5.2.1",
"eslint-plugin-react": "^7.37.4",
"eslint-plugin-react-hooks": "^5.1.0",
"eslint-plugin-react-refresh": "^0.4.12",
"jsdom": "^26.0.0",
"prettier": "^3.4.2",
"typescript": "^5.6.3",
"vite": "^5.4.9",
"vitest": "^2.1.3"
Expand Down
49 changes: 32 additions & 17 deletions src/refactoring/components/CartPage.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { CartItem, Coupon, Product } from '../../types.ts';
import { useCart } from "../hooks";
import { useCart } from '../hooks';

interface Props {
products: Product[];
Expand All @@ -14,19 +14,19 @@ export const CartPage = ({ products, coupons }: Props) => {
updateQuantity,
applyCoupon,
calculateTotal,
selectedCoupon
selectedCoupon,
} = useCart();

const getMaxDiscount = (discounts: { quantity: number; rate: number }[]) => {
return discounts.reduce((max, discount) => Math.max(max, discount.rate), 0);
};

const getRemainingStock = (product: Product) => {
const cartItem = cart.find(item => item.product.id === product.id);
const cartItem = cart.find((item) => item.product.id === product.id);
return product.stock - (cartItem?.quantity || 0);
};

const { totalBeforeDiscount, totalAfterDiscount, totalDiscount } = calculateTotal()
const { totalBeforeDiscount, totalAfterDiscount, totalDiscount } = calculateTotal();

const getAppliedDiscount = (item: CartItem) => {
const { discounts } = item.product;
Expand All @@ -47,16 +47,22 @@ export const CartPage = ({ products, coupons }: Props) => {
<div>
<h2 className="text-2xl font-semibold mb-4">상품 목록</h2>
<div className="space-y-2">
{products.map(product => {
{products.map((product) => {
const remainingStock = getRemainingStock(product);
return (
<div key={product.id} data-testid={`product-${product.id}`} className="bg-white p-3 rounded shadow">
<div
key={product.id}
data-testid={`product-${product.id}`}
className="bg-white p-3 rounded shadow"
>
<div className="flex justify-between items-center mb-2">
<span className="font-semibold">{product.name}</span>
<span className="text-gray-600">{product.price.toLocaleString()}원</span>
</div>
<div className="text-sm text-gray-500 mb-2">
<span className={`font-medium ${remainingStock > 0 ? 'text-green-600' : 'text-red-600'}`}>
<span
className={`font-medium ${remainingStock > 0 ? 'text-green-600' : 'text-red-600'}`}
>
재고: {remainingStock}개
</span>
{product.discounts.length > 0 && (
Expand Down Expand Up @@ -94,21 +100,24 @@ export const CartPage = ({ products, coupons }: Props) => {
<h2 className="text-2xl font-semibold mb-4">장바구니 내역</h2>

<div className="space-y-2">
{cart.map(item => {
{cart.map((item) => {
const appliedDiscount = getAppliedDiscount(item);
return (
<div key={item.product.id} className="flex justify-between items-center bg-white p-3 rounded shadow">
<div
key={item.product.id}
className="flex justify-between items-center bg-white p-3 rounded shadow"
>
<div>
<span className="font-semibold">{item.product.name}</span>
<br/>
<br />
<span className="text-sm text-gray-600">
{item.product.price}원 x {item.quantity}
{item.product.price}원 x {item.quantity}
{appliedDiscount > 0 && (
<span className="text-green-600 ml-1">
({(appliedDiscount * 100).toFixed(0)}% 할인 적용)
</span>
({(appliedDiscount * 100).toFixed(0)}% 할인 적용)
</span>
)}
</span>
</span>
</div>
<div>
<button
Expand Down Expand Up @@ -144,14 +153,20 @@ export const CartPage = ({ products, coupons }: Props) => {
<option value="">쿠폰 선택</option>
{coupons.map((coupon, index) => (
<option key={coupon.code} value={index}>
{coupon.name} - {coupon.discountType === 'amount' ? `${coupon.discountValue}원` : `${coupon.discountValue}%`}
{coupon.name} -{' '}
{coupon.discountType === 'amount'
? `${coupon.discountValue}원`
: `${coupon.discountValue}%`}
</option>
))}
</select>
{selectedCoupon && (
<p className="text-green-600">
적용된 쿠폰: {selectedCoupon.name}
({selectedCoupon.discountType === 'amount' ? `${selectedCoupon.discountValue}원` : `${selectedCoupon.discountValue}%`} 할인)
적용된 쿠폰: {selectedCoupon.name}(
{selectedCoupon.discountType === 'amount'
? `${selectedCoupon.discountValue}원`
: `${selectedCoupon.discountValue}%`}{' '}
할인)
</p>
)}
</div>
Expand Down
67 changes: 55 additions & 12 deletions src/refactoring/hooks/useCart.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,68 @@
// useCart.ts
import { useState } from "react";
import { CartItem, Coupon, Product } from "../../types";
import { calculateCartTotal, updateCartItemQuantity } from "../models/cart";
import { useState } from 'react';
import { CartItem, Coupon, Product } from '../../types';
import { calculateCartTotal, updateCartItemQuantity } from '../models/cart';

export const useCart = () => {
const [cart, setCart] = useState<CartItem[]>([]);
const [selectedCoupon, setSelectedCoupon] = useState<Coupon | null>(null);

const addToCart = (product: Product) => {};
// 장바구니에 제품을 추가해야 합니다.
const addToCart = (product: Product) => {
const existingItem = cart.find((item) => item.product.id === product.id);

const removeFromCart = (productId: string) => {};
if (existingItem) {
updateQuantity(product.id, existingItem.quantity + 1);
return;
}
setCart((cartItem) => [...cartItem, { product, quantity: 1 }]);
};

const updateQuantity = (productId: string, newQuantity: number) => {};
// 장바구니에서 제품을 제거해야 합니다.
const removeFromCart = (productId: string) => {
setCart(cart.filter((cartItem: Product) => cartItem.product.id !== productId));
};

const applyCoupon = (coupon: Coupon) => {};
// 제품 수량을 업데이트해야 합니다.
const updateQuantity = (productId: string, newQuantity: number) => {
setCart((prevCart) =>
prevCart.map((item) =>
item.product.id === productId ? { ...item, quantity: newQuantity } : item,
),
);
};

// 쿠폰을 적용해야지
const applyCoupon = (coupon: Coupon) => {
setSelectedCoupon(coupon);
};

const calculateTotal = () => ({
totalBeforeDiscount: 0,
totalAfterDiscount: 0,
totalDiscount: 0,
});
// 합계를 정확하게 계산해야 합니다.
const calculateTotal = () => {
// 할인 전 총액 계산
const totalBeforeDiscount = cart.reduce(
(totalPrice, cartItem) => totalPrice + cartItem.product.price * cartItem.quantity,
0,
);

// 할인 금액
const totalDiscount = selectedCoupon
? Math.min(
selectedCoupon.discountType === 'percentage'
? totalBeforeDiscount * (selectedCoupon.discountValue / 100)
: selectedCoupon.discountValue,
)
: 0;

// 최종 금액
const totalAfterDiscount = totalBeforeDiscount - totalDiscount;

return {
totalBeforeDiscount,
totalAfterDiscount,
totalDiscount,
};
};

return {
cart,
Expand Down
17 changes: 14 additions & 3 deletions src/refactoring/hooks/useCoupon.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
import { Coupon } from "../../types.ts";
import { useState } from "react";
import { Coupon } from '../../types.ts';
import { useState } from 'react';

export const useCoupons = (initialCoupons: Coupon[]) => {
return { coupons: [], addCoupon: () => undefined };
// 쿠폰을 초기화할 수 있다.
const [coupons, setCoupons] = useState<Coupon[]>(initialCoupons);

// 쿠폰을 추가할 수 있다.
const addCoupon = (newCoupon: Coupon) => {
setCoupons(prevCoupons => [...prevCoupons, newCoupon]);
};

return {
coupons,
addCoupon,
};
};
26 changes: 25 additions & 1 deletion src/refactoring/hooks/useProduct.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,29 @@ import { useState } from 'react';
import { Product } from '../../types.ts';

export const useProducts = (initialProducts: Product[]) => {
return { products: [], updateProduct: () => undefined, addProduct: () => undefined };
// 특정 제품으로 초기화 할 수 있다.
const [products, setProducts] = useState<Product[]>(initialProducts);

// 제품을 업데이트 할 수 있다.
const updateProduct = (updateProduct) => {
const newProductList = products.map((prevProduct) => {
if (prevProduct.id === updateProduct.id) {
return updateProduct;
} else {
return prevProduct;
}
});
setProducts(newProductList);
};

// 새로운 제품을 추가할 수 있다.
const addProduct = (newProduct: Product) => {
setProducts((prevProducts) => [...prevProducts, newProduct]);
};

return {
products,
updateProduct,
addProduct,
};
};
Loading
Loading