code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,53 @@ +package christmas.domain; + +import christmas.dto.BenefitDto; +import christmas.dto.GiftsDto; +import java.util.function.Supplier; + +public class Bill { + public static final int MINIMUM_ORDERS_PRICE = 10000; + public static final int EVENT_NOT_APPLIED_AMOUNT = 0; + + private final Discounts discounts; + private final Gifts gifts; + + public Bill(Discounts discounts, Gifts gifts) { + this.discounts = discounts; + this.gifts = gifts; + } + + public int getTotalBenefit(Orders orders) { + return getAmount(this::sumBenefit, orders); + } + + public int getDiscountPrice(Orders orders) { + return orders.getTotalPrice() - discounts.sumDiscount(); + } + + public GiftsDto getGiftDto() { + return new GiftsDto(gifts.getResult()); + } + + public BenefitDto getBenefitDto() { + return new BenefitDto(discounts.getResult(), gifts.sumPrice()); + } + + public String getBadgeName() { + return Badge.getNameByBenefit(sumBenefit()); + } + + private int sumBenefit() { + return discounts.sumDiscount() + gifts.sumPrice(); + } + + private boolean isEventApplicable(Orders orders) { + return orders.getTotalPrice() >= MINIMUM_ORDERS_PRICE; + } + + private <T> int getAmount(Supplier<T> supplier, Orders orders) { + if (isEventApplicable(orders)) { + return (int) supplier.get(); + } + return EVENT_NOT_APPLIED_AMOUNT; + } +}
Java
10000์› ์ด์ƒ์ด์—ฌ์•ผ๋งŒ ์ด๋ฒคํŠธ๊ฐ€ ์ ์šฉ๋˜๋Š” ๊ณตํ†ต ์กฐ๊ฑด์„ Bill์— ์œ„์น˜์‹œํ‚ค์…จ๋„ค์š”..! ํ•ด๋‹น ์กฐ๊ฑด์ด ์ด๋ฒคํŠธ๋ฅผ ์ ์šฉํ• ์ง€ ๋ง์ง€๋ฅผ ์ •ํ•œ๋‹ค๋Š” ์ธก๋ฉด์—์„œ Bill์— ์œ„์น˜ํ•˜๊ธฐ์—๋Š” ์ฑ…์ž„์ด ๋ฒ—์–ด๋‚œ ๋А๋‚Œ์ด ์žˆ๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๊ฐ ์ด๋ฒคํŠธ๋ฅผ ํด๋ž˜์Šค๋กœ ๊ตฌํ˜„ํ•˜์‹  ๊ฒƒ ๊ฐ™์€๋ฐ 10000์› ์ด์ƒ์ธ์ง€ ๊ฒ€์ฆํ•˜๋Š” ์ฝ”๋“œ์˜ ์œ„์น˜๋Š” DiscountPolicy๋“ค์— ์œ„์น˜์‹œํ‚ค์‹œ๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š” ๐Ÿค”
@@ -0,0 +1,53 @@ +package christmas.domain; + +import christmas.dto.BenefitDto; +import christmas.dto.GiftsDto; +import java.util.function.Supplier; + +public class Bill { + public static final int MINIMUM_ORDERS_PRICE = 10000; + public static final int EVENT_NOT_APPLIED_AMOUNT = 0; + + private final Discounts discounts; + private final Gifts gifts; + + public Bill(Discounts discounts, Gifts gifts) { + this.discounts = discounts; + this.gifts = gifts; + } + + public int getTotalBenefit(Orders orders) { + return getAmount(this::sumBenefit, orders); + } + + public int getDiscountPrice(Orders orders) { + return orders.getTotalPrice() - discounts.sumDiscount(); + } + + public GiftsDto getGiftDto() { + return new GiftsDto(gifts.getResult()); + } + + public BenefitDto getBenefitDto() { + return new BenefitDto(discounts.getResult(), gifts.sumPrice()); + } + + public String getBadgeName() { + return Badge.getNameByBenefit(sumBenefit()); + } + + private int sumBenefit() { + return discounts.sumDiscount() + gifts.sumPrice(); + } + + private boolean isEventApplicable(Orders orders) { + return orders.getTotalPrice() >= MINIMUM_ORDERS_PRICE; + } + + private <T> int getAmount(Supplier<T> supplier, Orders orders) { + if (isEventApplicable(orders)) { + return (int) supplier.get(); + } + return EVENT_NOT_APPLIED_AMOUNT; + } +}
Java
ํ• ์ธ๋œ ๊ฐ€๊ฒฉ์„ ๊ตฌํ•˜๋Š” ๋ฉ”์„œ๋“œ์˜ ์œ„์น˜๋Š” Orders๊ฐ€ ์ ์ ˆํ• ๊นŒ์š” Bill์ด ์ ์ ˆํ• ๊นŒ์š” ๐Ÿค” ์ €๋„ ์ด๊ฒƒ์„ ์ฐธ ๋งŽ์ด ๊ณ ๋ฏผํ–ˆ๋Š”๋ฐ์š” ..! ์ €๋Š” Order์— ์œ„์น˜์‹œํ‚ค๊ธด ํ–ˆ๋Š”๋ฐ ๊ด€๋ จํ•ด์„œ ํ•˜๋Š˜๋‹˜ ์ƒ๊ฐ๋„ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค! ๋˜ Orders๋ผ๋Š” ๋„๋ฉ”์ธ์„ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋ฐ›๊ณ  ์žˆ๋Š”๋ฐ int๋ฅผ ๋ฐ›๋Š” ๊ฒƒ์€ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋Š”์ง€๋„ ๊ถ๊ธˆํ•ด์š” ๊ด€๋ จํ•œ ๊ธฐ์ค€ ๊ณต์œ ํ•ด์ฃผ์‹œ๋ฉด ๊ฐ์‚ฌํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค ๐Ÿ™‡๐Ÿป
@@ -0,0 +1,25 @@ +package christmas.domain; + +import java.util.Map; + +public class Discount { + private final DiscountType type; + private final int amount; + + public Discount(DiscountType type, int amount) { + this.type = type; + this.amount = amount; + } + + public boolean isDiscount() { + return amount != 0; + } + + public int getAmount() { + return amount; + } + + public String getName() { + return type.getName(); + } +}
Java
ํ• ์ธ๋‚ด์—ญ์€ ํ• ์ธ ์ข…๋ฅ˜์™€ ํ• ์ธ ๊ธˆ์•ก์˜ ์–‘์œผ๋กœ ์ •์˜ํ•  ์ˆ˜ ์žˆ๊ตฐ์š” ๐Ÿ‘๐Ÿป ์ €๋„ ๋น„์Šทํ•˜๊ฒŒ ์ž‘์„ฑํ–ˆ์ง€๋งŒ ์ €๋Š” String ํƒ€์ž…์˜ description๊ณผ int amount๋กœ ์ž‘์„ฑํ–ˆ๋„ค์š”.. ์ด๋ ‡๊ฒŒ ๋ณด๋‹ˆ enum์œผ๋กœ ๊ด€๋ฆฌํ•˜์‹  ๊ฒƒ ์ •๋ง ์ข‹์•„๋ณด์ด๋„ค์š” ์„ธ์„ธํ•œ ์ฝ”๋“œ ์ž˜ ๋ฐฐ์šฐ๊ณ  ๊ฐ‘๋‹ˆ๋‹ค ๐Ÿ‘๐Ÿป ๐Ÿ‘๐Ÿป
@@ -0,0 +1,25 @@ +package christmas.domain; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class Discounts { + private final List<Discount> discounts; + + public Discounts(List<Discount> discounts) { + this.discounts = discounts; + } + + public int sumDiscount() { + return discounts.stream() + .mapToInt(Discount::getAmount) + .sum(); + } + + public Map<String, Integer> getResult() { + return discounts.stream() + .filter(Discount::isDiscount) + .collect(Collectors.toUnmodifiableMap(Discount::getName, Discount::getAmount)); + } +}
Java
์ผ๊ธ‰ ์ปฌ๋ ‰์…˜์„ ์ถ”์ถœํ•˜์‹œ๊ณ  ๊ด€๋ จ๋œ ๋กœ์ง๋„ ๊น”๋”ํ•˜๊ฒŒ ์ž˜ ๋ชจ์•„์ฃผ์‹  ๊ฒƒ ๊ฐ™์•„์š” ๐Ÿ‘๐Ÿป ์ข‹์•„๋ณด์ž…๋‹ˆ๋‹ค ๐Ÿ˜„
@@ -0,0 +1,21 @@ +package christmas.domain; + +public enum GiftType { + CHAMPAGNE("์ƒดํŽ˜์ธ", 25_000); + + private final String name; + private final int price; + + private GiftType(String name, int price) { + this.name = name; + this.price = price; + } + + public int calculatePrice(int quantity) { + return this.price * quantity; + } + + public String getName() { + return name; + } +}
Java
๋ฉ”๋‰ด์ด๊ธฐ๋„ ํ•˜๋ฉด์„œ ์ฆ์ •ํ’ˆ์ด๊ธฐ๋„ ํ•œ ์ƒดํŽ˜์ธ์€ GiftType์—๋„ ์œ„์น˜ํ•˜๊ณ  Menu์—๋„ ์œ„์น˜ํ•˜๋„ค์š” ๐Ÿค” ๋ณ€๊ฒฝ ์š”๊ตฌ์‚ฌํ•ญ์œผ๋กœ ์ƒดํŽ˜์ธ์˜ ํŒ๋งค๊ฐ€๊ฒฉ์ด ์ˆ˜์ •๋œ๋‹ค๋ฉด ํ•ด๋‹น ์œ„์น˜๋„ ์ˆ˜์ •๋˜์–ด์•ผ ํ•  ๊ฒƒ ๊ฐ™์•„์„œ ์ˆ˜์ • ์ง€์ ์ด ํผ์ง€๋Š” ๋ถ€๋ถ„์ด ์žˆ๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,57 @@ +package christmas.domain; + +import static christmas.domain.MenuType.APPETIZER; +import static christmas.domain.MenuType.DESSERT; +import static christmas.domain.MenuType.DRINK; +import static christmas.domain.MenuType.MAIN; + +import christmas.exception.InvalidOrderException; +import java.util.Arrays; + +public enum Menu { + MUSHROOM_SOUP("์–‘์†ก์ด์ˆ˜ํ”„", 6_000, APPETIZER), + TAPAS("ํƒ€ํŒŒ์Šค", 5_500, APPETIZER), + CAESAR_SALAD("์‹œ์ €์ƒ๋Ÿฌ๋“œ", 8_000, APPETIZER), + + T_BONE_STEAK("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 55_000, MAIN), + BBQ_RIBS("๋ฐ”๋น„ํ๋ฆฝ", 54_000, MAIN), + SEAFOOD_PASTA("ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", 35_000, MAIN), + CHRISTMAS_PASTA("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", 25_000, MAIN), + + CHOCOLATE_CAKE("์ดˆ์ฝ”์ผ€์ดํฌ", 15_000, DESSERT), + ICE_CREAM("์•„์ด์Šคํฌ๋ฆผ", 5_000, DESSERT), + + ZERO_COLA("์ œ๋กœ์ฝœ๋ผ", 3_000, DRINK), + RED_WINE("๋ ˆ๋“œ์™€์ธ", 60_000, DRINK), + CHAMPAGNE("์ƒดํŽ˜์ธ", 25_000, DRINK); + + private final String name; + private final int price; + private final MenuType type; + + Menu(String menuName, int price, MenuType type) { + this.name = menuName; + this.price = price; + this.type = type; + } + + public static Menu from(String menuName) { + return Arrays.stream(Menu.values()) + .filter(menu -> menuName.equals(menu.name)) + .findFirst() + .orElseThrow(InvalidOrderException::new); + } + + public boolean isEqualsMenuType(MenuType menuType) { + return this.type == menuType; + } + + public int calculatePrice(int quantity) { + return this.price * quantity; + } + + public String getName() { + return name; + } +} +
Java
๊ฒŒํ„ฐ๋ฅผ ์ตœ๋Œ€ํ•œ ์ง€์–‘ํ•˜์…จ๋„ค์š”..! ์ €๋Š” ์ด๋ ‡๊ฒŒ ๊นŒ์ง€ ์ƒ๊ฐ ๋ชปํ•ด๋ณด๊ณ  enum์—๋Š” Getter๋ฅผ ์ „๋ถ€ ์—ด์—ˆ๋„ค์š” ๐Ÿ˜ญ ์ข‹์•„๋ณด์ž…๋‹ˆ๋‹ค! ๐Ÿ‘๐Ÿป
@@ -0,0 +1,50 @@ +package christmas.domain; + +import static christmas.exception.ErrorMessages.INVALID_ORDER; + +import christmas.utils.IntegerConverter; +import christmas.exception.InvalidOrderException; + +public class Order { + public static final int MIN_ORDER_QUANTITY = 1; + + private final Menu menu; + private final int quantity; + + public Order(String menuName, String quantity) { + this.menu = Menu.from(menuName); + this.quantity = convertType(quantity); + + validateMinQuantity(); + } + + private int convertType(String quantity) { + return IntegerConverter.convert(quantity, INVALID_ORDER); + } + + private void validateMinQuantity() { + if (quantity < MIN_ORDER_QUANTITY) { + throw new InvalidOrderException(); + } + } + + public boolean isEqualsMenuType(MenuType type) { + return menu.isEqualsMenuType(type); + } + + public int calculatePrice() { + return menu.calculatePrice(quantity); + } + + public String getMenuName() { + return menu.getName(); + } + + public int getQuantity() { + return quantity; + } + + public Menu getMenu() { + return menu; + } +}
Java
String์œผ๋กœ ๋“ค์–ด์˜จ quantity๋ฅผ ์ •์ˆ˜๋กœ ์ปจ๋ฒ„ํŒ… ํ•˜๊ณ  ์ƒ์„ฑ์ž๋ฅผ ํ†ตํ•ด ํ• ๋‹น์ด ๊ฐ€๋Šฅํ•˜๋„๋ก ๋ณ€ํ™˜ํ•ด์ฃผ๋Š” ๋ถ€๋ถ„์ด๋„ค์š”! ๋„๋ฉ”์ธ ๊ด€๋ จ ๋กœ์ง์ด ์•„๋‹˜์—๋„ Order ๋„๋ฉ”์ธ์— ์œ„์น˜ํ•˜์—ฌ Order ๋„๋ฉ”์ธ์˜ ์ฑ…์ž„์„ ํ๋ฆด ์ˆ˜๋„ ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ•˜๋Š”๋ฐ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š” ๐Ÿค” ๋ณ€ํ™˜์€ ์™ธ๋ถ€์—์„œ ์ผ์–ด๋‚˜๊ณ  ์ƒ์„ฑ์š”์ฒญ์„ ๋ฐ›์„ ๋•Œ์—๋Š” ์ •์ œ๋œ ์ƒํƒœ๋กœ ๋ฐ›์•„์•ผ ํ•˜์ง€ ์•Š๋‚˜๋ผ๋Š” ๊ฐœ์ธ์ ์ธ ์ƒ๊ฐ์ž…๋‹ˆ๋‹ค ๐Ÿ‘๐Ÿป
@@ -0,0 +1,104 @@ +package christmas.domain; + +import christmas.dto.OrdersDto; +import christmas.exception.InvalidOrderException; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class Orders { + public static final String ORDER_DELIMITER = ","; + public static final String MENU_AND_QUANTITY_DELIMITER = "-"; + public static final int MAX_ORDER_QUANTITY = 20; + + private final List<Order> orders; + + public Orders(String orders) { + validateFormat(orders); + this.orders = createOrders(orders); + + validateOverQuantity(); + validateDuplicate(); + validateAllDrink(); + } + + private List<Order> createOrders(String value) { + return getOrdersStream(value) + .map(order -> new Order(order[0], order[1])) + .toList(); + } + + private void validateFormat(String value) { + if (isInvalidFormat(value)) { + throw new InvalidOrderException(); + } + } + + private boolean isInvalidFormat(String value) { + return getOrdersStream(value) + .anyMatch(order -> order.length != 2); + } + + private Stream<String[]> getOrdersStream(String value) { + return Arrays.stream(value.split(ORDER_DELIMITER)) + .map(order -> order.split(MENU_AND_QUANTITY_DELIMITER)); + } + + private void validateOverQuantity() { + if (sumOrderQuantity() > MAX_ORDER_QUANTITY) { + throw new InvalidOrderException(); + } + } + + private int sumOrderQuantity() { + return orders.stream() + .mapToInt(Order::getQuantity) + .sum(); + } + + private void validateDuplicate() { + if (countUniqueOrderMenu() != orders.size()) { + throw new InvalidOrderException(); + } + } + + private int countUniqueOrderMenu() { + return (int) orders.stream() + .map(Order::getMenu) + .distinct() + .count(); + } + + private void validateAllDrink() { + if (isAllDrinkMenu()) { + throw new InvalidOrderException(); + } + } + + private boolean isAllDrinkMenu() { + return orders.stream() + .allMatch(order -> order.isEqualsMenuType(MenuType.DRINK)); + } + + public int getTotalPrice() { + return orders.stream() + .mapToInt(Order::calculatePrice) + .sum(); + } + + public int getQuantityByMenuType(MenuType type) { + return orders.stream() + .filter(order -> order.isEqualsMenuType(type)) + .mapToInt(Order::getQuantity) + .sum(); + } + + public OrdersDto getOrders() { + Map<String, Integer> result = orders.stream() + .collect(Collectors.toUnmodifiableMap(Order::getMenuName, Order::getQuantity)); + + return new OrdersDto(result); + } +}
Java
๋ฐ”๋กœ ์œ„์™€ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ String์„ ๊ธฐ๋ฐ˜์œผ๋กœ ์ƒ์„ฑํ•˜๋ ค๊ณ  ํ•˜๋‹ค๋ณด๋‹ˆ String์„ splitํ•˜๊ณ  ๊ฐ’์„ ํŒŒ์‹ฑํ•˜๋Š” ๋“ฑ์˜ ์ฑ…์ž„์ด Orders ๋„๋ฉ”์ธ์— ์œ„์น˜ํ•˜๋„๋ก ์œ ๋„ํ•˜๊ณ  ์žˆ๋„ค์š”! List<Order>๋ฅผ ๋ฐ›์•„์„œ ๋ฐ”๋กœ ์ƒ์„ฑํ•˜๋„๋ก ์œ ๋„ํ•˜์‹œ๋Š” ๊ฒƒ๋„ ์ข‹์•„๋ณด์ž…๋‹ˆ๋‹ค ๐Ÿ˜„
@@ -0,0 +1,48 @@ +package christmas.domain; + +import christmas.exception.InvalidDateException; +import java.time.DayOfWeek; +import java.time.LocalDate; +import java.util.List; + +public class VisitDate { + private static final int YEAR = 2023; + public static final int MONTH = 12; + private static final int MIN_DATE = 1; + private static final int MAX_DATE = 31; + + private final int date; + + public VisitDate(int date) { + validateDateRange(date); + this.date = date; + } + + private void validateDateRange(int date) { + if (date < MIN_DATE || date > MAX_DATE) { + throw new InvalidDateException(); + } + } + + public DayOfWeek getDayOfWeek() { + LocalDate localDate = LocalDate.of(YEAR, MONTH, date); + return localDate.getDayOfWeek(); + } + + public boolean isContainDayOfDay(List<DayOfWeek> weekDay) { + DayOfWeek dayOfWeek = getDayOfWeek(); + return weekDay.contains(dayOfWeek); + } + + public boolean isEqualsDate(int date) { + return this.date == date; + } + + public boolean isNotAfter(int date) { + return this.date <= date; + } + + public int calculateDiscount(int discountAmount) { + return (date - 1) * discountAmount; + } +}
Java
์ฃผ๋ง์ธ์ง€ ํ‰์ผ์ธ์ง€ ๋ฌผ์–ด๋ณด๊ธฐ ์œ„ํ•ด์„œ getDayOfWeek๋ฅผ ์‚ฌ์šฉํ•˜์‹  ๊ฒƒ ๊ฐ™์€๋ฐ isWeekend()์™€ ๊ฐ™์€ ๋ฉ”์„œ๋“œ๊ฐ€ TDA ์ธก๋ฉด์—์„œ ์ข‹์•„๋ณด์ธ๋‹ค๋Š” ์ƒ๊ฐ์ž…๋‹ˆ๋‹ค ๐Ÿ˜„
@@ -0,0 +1,27 @@ +package christmas.domain.policy.discount; + +import christmas.domain.Orders; +import christmas.domain.VisitDate; + +public class DdayDiscountPolicy implements DiscountPolicy { + public static final int CHRISTMAS_DATE = 25; + public static final int DISCOUNT_AMOUNT = 1000; + public static final int ADDITIONAL_DISCOUNT_AMOUNT = 100; + public static final int NOT_DISCOUNT_AMOUNT = 0; + + @Override + public int discount(VisitDate visitDate, Orders orders) { + if (isNotAfter(visitDate)) { + return calculateDiscount(visitDate); + } + return NOT_DISCOUNT_AMOUNT; + } + + private boolean isNotAfter(VisitDate visitDate) { + return visitDate.isNotAfter(CHRISTMAS_DATE); + } + + private int calculateDiscount(VisitDate visitDate) { + return DISCOUNT_AMOUNT + visitDate.calculateDiscount(ADDITIONAL_DISCOUNT_AMOUNT); + } +}
Java
์ถ”์ƒ ํด๋ž˜์Šค ์ „ํ™˜ ๋„ˆ๋ฌด ์ข‹์€ ์•„์ด๋””์–ด์ธ๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์ข€ ๋” ์ฐพ์•„๋ณด๋‹ˆ ์ธํ„ฐํŽ˜์ด์Šค์— default ๋ฉ”์†Œ๋“œ๋ฅผ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋”๋ผ๊ตฌ์š”. ์ธํ„ฐํŽ˜์ด์Šค default ๋ฉ”์†Œ๋“œ๋ฅผ ๊ตฌํ˜„ํ•ด ์กฐ๊ฑด์„ ๊ฒ€์‚ฌํ•  ์ˆ˜ ์žˆ์„๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ์ธํ„ฐํŽ˜์ด์Šค์˜ ์žฅ์ ๋„ ๊ฐ€์ ธ๊ฐ€๊ณ , ์กฐ๊ฑด ๊ฒ€์‚ฌ์˜ ์ฑ…์ž„๋„ ๋ถ€์—ฌํ•  ์ˆ˜ ์žˆ์„๊ฑฐ ๊ฐ™๋„ค์š”. ๋ฆฌ๋ทฐ ๋•๋ถ„์— ์ถ”์ƒ ํด๋ž˜์Šค, ์ธํ„ฐํŽ˜์ด์Šค์— ๋Œ€ํ•ด ์ฐพ์•„๋ณด๊ณ  ๊ณต๋ถ€ํ•  ์ˆ˜ ์žˆ์—ˆ์Šต๋‹ˆ๋‹ค ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿ˜Š
@@ -0,0 +1,53 @@ +package christmas.domain; + +import christmas.dto.BenefitDto; +import christmas.dto.GiftsDto; +import java.util.function.Supplier; + +public class Bill { + public static final int MINIMUM_ORDERS_PRICE = 10000; + public static final int EVENT_NOT_APPLIED_AMOUNT = 0; + + private final Discounts discounts; + private final Gifts gifts; + + public Bill(Discounts discounts, Gifts gifts) { + this.discounts = discounts; + this.gifts = gifts; + } + + public int getTotalBenefit(Orders orders) { + return getAmount(this::sumBenefit, orders); + } + + public int getDiscountPrice(Orders orders) { + return orders.getTotalPrice() - discounts.sumDiscount(); + } + + public GiftsDto getGiftDto() { + return new GiftsDto(gifts.getResult()); + } + + public BenefitDto getBenefitDto() { + return new BenefitDto(discounts.getResult(), gifts.sumPrice()); + } + + public String getBadgeName() { + return Badge.getNameByBenefit(sumBenefit()); + } + + private int sumBenefit() { + return discounts.sumDiscount() + gifts.sumPrice(); + } + + private boolean isEventApplicable(Orders orders) { + return orders.getTotalPrice() >= MINIMUM_ORDERS_PRICE; + } + + private <T> int getAmount(Supplier<T> supplier, Orders orders) { + if (isEventApplicable(orders)) { + return (int) supplier.get(); + } + return EVENT_NOT_APPLIED_AMOUNT; + } +}
Java
> Dto๋Š” ๋ณ€๋™์„ฑ์ด ํฐ ๊ฐ์ฒด๋ผ๊ณ  ์ƒ๊ฐํ•ด์„œ domain์ด ์˜์กดํ•˜๋Š” ํ˜•ํƒœ๋Š” ์ข‹์ง€ ์•Š๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. > ์ค‘์š”ํ•œ ๊ฐ์ฒด๊ฐ€(๋„๋ฉ”์ธ) ๋œ ์ค‘์š”ํ•œ ๊ฐ์ฒด(DTO)๋ฅผ ์˜์กดํ•˜๋Š” ๊ฒƒ์ด ์ข‹์ง€ ์•Š๋‹ค ๋„ˆ๋ฌด ๊ณต๊ฐ๋˜๋Š” ๋‚ด์šฉ์ด๋„ค์š”! ํ˜„์žฌ๋Š” DTO์™€ Domain์˜ ๊ฐ•ํ•œ ๊ฒฐํ•ฉ๋„๋กœ ์ธํ•ด DTO ๋ณ€๊ฒฝ ์‹œ Domain ์ฝ”๋“œ๋ฅผ ์ˆ˜์ •ํ•ด์•ผํ•œ๋‹ค๋Š” ๋ฌธ์ œ๊ฐ€ ์žˆ๋Š”๊ฑฐ ๊ฐ™์•„์š”. Domain์—์„œ๋Š” DTO ์ƒ์„ฑ์— ํ•„์š”ํ•œ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๊ณ , Controller์—์„œ DTO๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๊ฒƒ์ด ์ข‹์„๊ฑฐ ๊ฐ™๋„ค์š”!!! ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,36 @@ +package christmas.domain; + +import christmas.exception.NotExistsBadgeException; +import java.util.Arrays; + +public enum Badge { + SANTA("์‚ฐํƒ€", 20000), + TREE("ํŠธ๋ฆฌ", 10000), + STAR("๋ณ„", 5000), + NONE("์—†์Œ", 0), + ; + + private final String name; + private final int minimumAmount; + + private Badge(String name, int minimumAmount) { + this.name = name; + this.minimumAmount = minimumAmount; + } + + public static String getNameByBenefit(int amount) { + return from(amount).name; + } + + public static Badge from(int amount) { + return Arrays.stream(Badge.values()) + .filter(badge -> badge.isGreaterThan(amount)) + .findFirst() + .orElseThrow(NotExistsBadgeException::new); + } + + private boolean isGreaterThan(int benefitAmount) { + return this.minimumAmount <= benefitAmount; + } +} +
Java
์ด ๋ถ€๋ถ„์€ ๊ณ ๋ ค ํ•ด๋ณด์ง€ ๋ชปํ–ˆ๋„ค์š” ๐Ÿ˜ฎ ํ˜„์žฌ Enum์€ minimumAmount ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ƒ์ˆ˜๋ฅผ ์„ ์–ธํ–ˆ๊ธฐ ๋•Œ๋ฌธ์— ๋ฌธ์ œ๊ฐ€ ์—†์ง€๋งŒ, ์ถ”ํ›„ ๋‹ค๋ฅธ ์‚ฌ๋žŒ์ด ํ•ด๋‹น ์ฝ”๋“œ์— ๋Œ€ํ•œ ์ถ”๊ฐ€์ ์ธ ๊ตฌํ˜„์„ ํ•˜๋Š” ๊ฒฝ์šฐ ์ƒ์ˆ˜ ์„ ์–ธ ๊ทœ์น™์„ ์ธ์ง€ํ•˜์ง€ ๋ชปํ•  ์ˆ˜ ์žˆ์„๊ฑฐ ๊ฐ™๋„ค์š”. @Arachneee ๋ง์”€์ฒ˜๋Ÿผ ์–ด๋– ํ•œ ์ƒํ™ฉ์—์„œ๋„ ์ฝ”๋“œ์˜ ๋™์ž‘์„ ๋ช…ํ™•ํ•˜๊ฒŒ ํ•˜๊ธฐ ์œ„ํ•ด ์ •๋ ฌํ•˜๋Š” ์ฝ”๋“œ๋ฅผ ์ถ”๊ฐ€ํ•˜๋Š” ๊ฒƒ์ด ์ข‹์„๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ข‹์€ ๋ฆฌ๋ทฐ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,18 @@ +package christmas.domain; + +public enum DiscountType { + CHRISTMAS_DDAY("ํฌ๋ฆฌ์Šค๋งˆ์Šค ๋””๋ฐ์ด ํ• ์ธ"), + WEEKDAY("ํ‰์ผ ํ• ์ธ"), + WEEKEND("์ฃผ๋ง ํ• ์ธ"), + SPECIAL("ํŠน๋ณ„ ํ• ์ธ"); + + private final String name; + + DiscountType(String name) { + this.name = name; + } + + public String getName() { + return name; + } +}
Java
์ €๋„ ๊ฐ DiscountPolicy ๊ตฌํ˜„์ฒด์—์„œ ํ• ์ธ ์ œ๋ชฉ์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ตฌ์กฐ๋ฅผ ์ƒ๊ฐํ•ด๋ดค๋Š”๋ฐ, ์ด ๊ตฌ์กฐ๋Š” DiscountPolicy์™€ ํ• ์ธ ์ œ๋ชฉ์ด ์ผ๋Œ€์ผ๋กœ ๋งคํ•‘๋˜๊ธฐ ๋•Œ๋ฌธ์— DiscountPolicy๋ฅผ ์—ฌ๋Ÿฌ ํ• ์ธ์—์„œ ์žฌ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๋‹ค๋Š” ๋‹จ์ ์ด ์žˆ์—ˆ์Šต๋‹ˆ๋‹ค. ์ถ”ํ›„ ์ถ”๊ฐ€๋  ์ˆ˜ ์žˆ๋Š” ์š”๊ตฌ์‚ฌํ•ญ์„ ๊ณ ๋ คํ–ˆ์„ ๋•Œ ํ™•์žฅ์„ฑ ๋ฉด์—์„œ ์ข‹์ง€ ์•Š์„๊ฒƒ์ด๋ผ ์ƒ๊ฐํ•ด DiscountPolicy์™€ ํ• ์ธ ์ œ๋ชฉ์„ ๋”ฐ๋กœ ๊ด€๋ฆฌํ–ˆ์Šต๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ, ์–ด๋–ค ์ฝ”๋“œ๊ฐ€ ๋” ์ข‹์€ ์ฝ”๋“œ์ธ์ง€ ์ •๋‹ต์€ ์—†๋Š”๊ฑฐ ๊ฐ™์•„์š”. ์ด๋ฒˆ ๋ฏธ์…˜์„ ์ง„ํ–‰ํ•˜๋ฉฐ ์š”๊ตฌ์‚ฌํ•ญ ํ™•์žฅ์„ ์–ผ๋งˆ๋‚˜ ๊ณ ๋ คํ•ด์•ผํ• ์ง€์— ๋Œ€ํ•œ ๊ณ ๋ฏผ์ด ๋งŽ์•˜๊ธฐ์— ์ œ ์ƒ๊ฐ์„ ํ•œ ๋ฒˆ ๊ณต์œ ๋“œ๋ ค๋ด…๋‹ˆ๋‹ค! ์ถ”๊ฐ€๋กœ, Enum์œผ๋กœ ํ• ์ธ ์ข…๋ฅ˜๋ฅผ ํ•œ ๊ณณ์—์„œ ๊ด€๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ๊ฐ€๋…์„ฑ ๋ฉด์—์„œ ๋” ์ข‹๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ์–ด์š”. ๋˜ํ•œ, ํ• ์ธ ์ œ๋ชฉ์„ String์œผ๋กœ ๊ด€๋ฆฌํ•˜๋ฉด ์ž˜๋ชป๋œ ๊ฐ’์ด ๋“ค์–ด๊ฐˆ ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— Enum์„ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค. ๐Ÿ˜€
@@ -0,0 +1,53 @@ +package christmas.domain; + +import christmas.dto.BenefitDto; +import christmas.dto.GiftsDto; +import java.util.function.Supplier; + +public class Bill { + public static final int MINIMUM_ORDERS_PRICE = 10000; + public static final int EVENT_NOT_APPLIED_AMOUNT = 0; + + private final Discounts discounts; + private final Gifts gifts; + + public Bill(Discounts discounts, Gifts gifts) { + this.discounts = discounts; + this.gifts = gifts; + } + + public int getTotalBenefit(Orders orders) { + return getAmount(this::sumBenefit, orders); + } + + public int getDiscountPrice(Orders orders) { + return orders.getTotalPrice() - discounts.sumDiscount(); + } + + public GiftsDto getGiftDto() { + return new GiftsDto(gifts.getResult()); + } + + public BenefitDto getBenefitDto() { + return new BenefitDto(discounts.getResult(), gifts.sumPrice()); + } + + public String getBadgeName() { + return Badge.getNameByBenefit(sumBenefit()); + } + + private int sumBenefit() { + return discounts.sumDiscount() + gifts.sumPrice(); + } + + private boolean isEventApplicable(Orders orders) { + return orders.getTotalPrice() >= MINIMUM_ORDERS_PRICE; + } + + private <T> int getAmount(Supplier<T> supplier, Orders orders) { + if (isEventApplicable(orders)) { + return (int) supplier.get(); + } + return EVENT_NOT_APPLIED_AMOUNT; + } +}
Java
@Libienz ๋ง์”€์ฒ˜๋Ÿผ Bill๋Š” ์ฃผ๋ฌธ์— ๋Œ€ํ•œ ํ• ์ธ ๋‚ด์—ญ์„ ๊ฐ–๋Š” ๊ฐ์ฒด์ธ๋ฐ ํ•ด๋‹น ๊ฐ์ฒด์—์„œ ํ• ์ธ ์กฐ๊ฑด์„ ๊ฒ€์‚ฌํ•˜๋Š” ๊ฒƒ์€ ๋งŽ์€ ์ฑ…์ž„์„ ๊ฐ–๊ณ  ์žˆ๋Š”๊ฑฐ ๊ฐ™๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“œ๋„ค์š”. DiscountPolicy์˜ default ๋ฉ”์„œ๋“œ๋กœ ์กฐ๊ฑด์„ ๊ฒ€์‚ฌํ•˜๋Š” ๊ฒƒ์ด ์ข‹์„๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค ์ข‹์€ ๋ฆฌ๋ทฐ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿ˜€
@@ -0,0 +1,53 @@ +package christmas.domain; + +import christmas.dto.BenefitDto; +import christmas.dto.GiftsDto; +import java.util.function.Supplier; + +public class Bill { + public static final int MINIMUM_ORDERS_PRICE = 10000; + public static final int EVENT_NOT_APPLIED_AMOUNT = 0; + + private final Discounts discounts; + private final Gifts gifts; + + public Bill(Discounts discounts, Gifts gifts) { + this.discounts = discounts; + this.gifts = gifts; + } + + public int getTotalBenefit(Orders orders) { + return getAmount(this::sumBenefit, orders); + } + + public int getDiscountPrice(Orders orders) { + return orders.getTotalPrice() - discounts.sumDiscount(); + } + + public GiftsDto getGiftDto() { + return new GiftsDto(gifts.getResult()); + } + + public BenefitDto getBenefitDto() { + return new BenefitDto(discounts.getResult(), gifts.sumPrice()); + } + + public String getBadgeName() { + return Badge.getNameByBenefit(sumBenefit()); + } + + private int sumBenefit() { + return discounts.sumDiscount() + gifts.sumPrice(); + } + + private boolean isEventApplicable(Orders orders) { + return orders.getTotalPrice() >= MINIMUM_ORDERS_PRICE; + } + + private <T> int getAmount(Supplier<T> supplier, Orders orders) { + if (isEventApplicable(orders)) { + return (int) supplier.get(); + } + return EVENT_NOT_APPLIED_AMOUNT; + } +}
Java
Bill ๊ฐ์ฒด๋Š” Order์™€ Discount, Gift ๊ฐ์ฒด ์‚ฌ์ด์˜ ํ˜‘๋ ฅ์„ ์œ„ํ•œ ์ค‘๊ฐ„ ๊ฐ์ฒด๋กœ, ์ฃผ๋ฌธ์— ๋Œ€ํ•œ ํ• ์ธ ํ˜œํƒ์„ ๋ฐ˜ํ™˜ํ•˜๊ธฐ ์œ„ํ•ด ์„ค๊ณ„ํ–ˆ์–ด์š”. ๋”ฐ๋ผ์„œ, ํ• ์ธ ํ›„ ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก์— ๋Œ€ํ•œ ๊ณ„์‚ฐ์€ Bill ๊ฐ์ฒด์˜ ์ฑ…์ž„์ด๋ผ๊ณ  ์ƒ๊ฐํ–ˆ์Šต๋‹ˆ๋‹ค. ์ฝ”๋“œ๋ฅผ ๋‹ค์‹œ ์‚ดํŽด๋ณด๋‹ˆ ์•„๋ž˜์™€ ๊ฐ™์ด Order ๊ฐ์ฒด์— ํ• ์ธ ๊ธˆ์•ก์„ ๋„˜๊ฒจ์คŒ์œผ๋กœ์จ Order ๊ฐ์ฒด ๋‚ด๋ถ€์—์„œ ํ• ์ธ๋œ ๊ฐ€๊ฒฉ์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฐฉ๋ฒ•๋„ ์žˆ์„๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์•„๋ž˜ ์ฝ”๋“œ๊ฐ€ ๋” ๊ฐ์ฒด๊ฐ„ ๋ฉ”์‹œ์ง€๋ฅผ ์ฃผ๊ณ ๋ฐ›์œผ๋ฉฐ ํ˜‘๋ ฅํ•˜๋Š” ๊ตฌ์กฐ๋ผ๊ณ  ์ƒ๊ฐ๋˜๋„ค์š”. ๋•๋ถ„์— ๋” ๋‚˜์€ ์ฝ”๋“œ๋กœ ๋ฆฌํŒฉํ† ๋ง ํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋˜์—ˆ๋„ค์š” ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿ˜ถ ```java public int getDiscountPrice(Orders orders) { int discount = discounts.sumDiscount(); return orders.getDiscountPrice(discount); } ``` ๊ทธ๋ฆฌ๊ณ , Bill ๊ฐ์ฒด๋Š” ์ค‘๊ฐ„ ๊ฐ์ฒด์ด๊ธฐ ๋•Œ๋ฌธ์— Orders ๋„๋ฉ”์ธ์„ ์•Œ์•„๋„ ๋œ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ์–ด์š”. ๋งŒ์•ฝ, Orders๊ฐ€ ์•„๋‹Œ ์ด ์ฃผ๋ฌธ ๊ธˆ์•ก์„ ์ธ์ž๋กœ ๋ฐ›๋Š”๋‹ค๋ฉด ์™ธ๋ถ€์—์„œ getTotalPrice ๋ฉ”์†Œ๋“œ๋ฅผ ํ˜ธ์ถœํ•ด์•ผํ•˜๋Š”๋ฐ, ์™ธ๋ถ€์—์„œ ์ด ์ฃผ๋ฌธ ๊ธˆ์•ก์„ ์•Œ๊ณ ์žˆ์–ด์•ผ ํ• ๊นŒ? ๋ผ๋Š” ์˜๋ฌธ์ด ๋“ค์—ˆ์Šต๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ, Restaurant ๊ฐ์ฒด๋Š” ๋ฐฉ๋ฌธ ๋‚ ์งœ์™€ ์ฃผ๋ฌธ์„ ๋ฐ›๊ธฐ๋งŒ ํ•˜๊ณ , ์ด๋ฅผ Bill ๊ฐ์ฒด์—๊ฒŒ ํ• ์ธ๋œ ๊ฐ€๊ฒฉ์„ ์•Œ๋ ค์ค˜ ~ ๋ผ๊ณ  ์ฑ…์ž„์„ ์œ„์ž„ํ•˜๋Š” ๊ฒƒ์ด ๋” ๊ฐ์ฒด์ง€ํ–ฅ์Šค๋Ÿฝ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ์–ด์š”. @Libienz ๋ฆฌ๋ทฐ๋ฅผ ํ†ตํ•ด ์ œ ์ฝ”๋“œ์— ๋Œ€ํ•œ ๊ทผ๊ฑฐ๋ฅผ ๋‹ค์‹œ ํ•œ๋ฒˆ ์ƒ๊ฐํ•ด๋ณผ ์ˆ˜ ์žˆ์—ˆ๋„ค์š” ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค !!!!
@@ -0,0 +1,50 @@ +package christmas.domain; + +import static christmas.exception.ErrorMessages.INVALID_ORDER; + +import christmas.utils.IntegerConverter; +import christmas.exception.InvalidOrderException; + +public class Order { + public static final int MIN_ORDER_QUANTITY = 1; + + private final Menu menu; + private final int quantity; + + public Order(String menuName, String quantity) { + this.menu = Menu.from(menuName); + this.quantity = convertType(quantity); + + validateMinQuantity(); + } + + private int convertType(String quantity) { + return IntegerConverter.convert(quantity, INVALID_ORDER); + } + + private void validateMinQuantity() { + if (quantity < MIN_ORDER_QUANTITY) { + throw new InvalidOrderException(); + } + } + + public boolean isEqualsMenuType(MenuType type) { + return menu.isEqualsMenuType(type); + } + + public int calculatePrice() { + return menu.calculatePrice(quantity); + } + + public String getMenuName() { + return menu.getName(); + } + + public int getQuantity() { + return quantity; + } + + public Menu getMenu() { + return menu; + } +}
Java
@Libienz ๋ฆฌ๋ทฐ์— ์ ๊ทน ๊ณต๊ฐํ•˜๋Š” ๋ฐ”์ž…๋‹ˆ๋‹ค! ์ž…๋ ฅ์— ๋Œ€ํ•œ ํ˜•์‹์€ View ๊ณ„์ธต์—์„œ ๊ฒ€์ฆํ•˜๋Š” ๊ฒƒ์ด ๋” ์ข‹๋‹ค๊ณ  ์ƒ๊ฐ๋˜๋„ค์š”. ํ˜„์žฌ๋Š” ์ž…๋ ฅ๊ฐ’์„ ๊ทธ๋Œ€๋กœ ์ƒ์„ฑ์ž ์ธ์ž๋กœ ์ „๋‹ฌํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋„๋ฉ”์ธ ๊ฐ์ฒด ๋‚ด๋ถ€์—์„œ ํ˜•์‹์— ๋งž์ถฐ ๊ฐ’์„ ํŒŒ์‹ฑํ•˜๋Š” ๋กœ์ง์„ ์ˆ˜ํ–‰ํ•˜๊ณ  ์žˆ์–ด์š”. @Libienz ๋ง์”€์ฒ˜๋Ÿผ ์ด๋Ÿฌํ•œ ๊ตฌ์กฐ๋Š” ๋„๋ฉ”์ธ์˜ ์ฑ…์ž„์„ ํ๋ฆด ์ˆ˜ ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ•ด์š”. ์ถ”๊ฐ€๋กœ, ํŒŒ์‹ฑ ๋กœ์ง์— ์˜ํ•ด ๋„๋ฉ”์ธ ๋กœ์ง์„ ํ•œ ๋ˆˆ์— ํŒŒ์•…ํ•  ์ˆ˜ ์—†๋‹ค๋Š” ๋‹จ์ ์ด ์žˆ์„๊ฑฐ ๊ฐ™์•„์š”. ๊ทผํฌ๋‹˜ ์ฝ”๋“œ๋ฅผ ๋ณด๋‹ˆ ์ž…๋ ฅ๊ฐ’์— ๋Œ€ํ•œ ํ˜•์‹ ๊ฒ€์ฆ ๋ฐ ํŒŒ์‹ฑ ๊ฐ์ฒด๊ฐ€ ๋ถ„๋ฆฌ๋˜์–ด ์žˆ๋”๋ผ๊ตฌ์š”. ์ •๋ง ์ธ์ƒ๊นŠ๊ฒŒ ๋ดค์Šต๋‹ˆ๋‹ค. ์ €๋„ ์•ž์œผ๋กœ๋Š” View ๊ณ„์ธต์œผ๋กœ ํ•ด๋‹น ๋กœ์ง์„ ๋ถ„๋ฆฌํ•ด ๋ณผ ์ƒ๊ฐ์ž…๋‹ˆ๋‹ค. ์ข‹์€ ๋ฆฌ๋ทฐ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿ‘๐Ÿป
@@ -0,0 +1,48 @@ +package christmas.domain; + +import christmas.exception.InvalidDateException; +import java.time.DayOfWeek; +import java.time.LocalDate; +import java.util.List; + +public class VisitDate { + private static final int YEAR = 2023; + public static final int MONTH = 12; + private static final int MIN_DATE = 1; + private static final int MAX_DATE = 31; + + private final int date; + + public VisitDate(int date) { + validateDateRange(date); + this.date = date; + } + + private void validateDateRange(int date) { + if (date < MIN_DATE || date > MAX_DATE) { + throw new InvalidDateException(); + } + } + + public DayOfWeek getDayOfWeek() { + LocalDate localDate = LocalDate.of(YEAR, MONTH, date); + return localDate.getDayOfWeek(); + } + + public boolean isContainDayOfDay(List<DayOfWeek> weekDay) { + DayOfWeek dayOfWeek = getDayOfWeek(); + return weekDay.contains(dayOfWeek); + } + + public boolean isEqualsDate(int date) { + return this.date == date; + } + + public boolean isNotAfter(int date) { + return this.date <= date; + } + + public int calculateDiscount(int discountAmount) { + return (date - 1) * discountAmount; + } +}
Java
์—‡ ์ด ๋ฉ”์†Œ๋“œ๋Š” VisitDate ๋‚ด๋ถ€์—์„œ๋งŒ ์‚ฌ์šฉํ•˜๋Š” ๋ฉ”์†Œ๋“œ์ธ๋ฐ ์ ‘๊ทผ ์ œํ•œ์ž๋ฅผ ์ž˜๋ชป ์„ค์ •ํ–ˆ๊ตฐ์š” .. ์„ธ์„ธํ•œ ๋ฆฌ๋ทฐ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค :)
@@ -0,0 +1,53 @@ +package christmas.domain; + +import christmas.dto.BenefitDto; +import christmas.dto.GiftsDto; +import java.util.function.Supplier; + +public class Bill { + public static final int MINIMUM_ORDERS_PRICE = 10000; + public static final int EVENT_NOT_APPLIED_AMOUNT = 0; + + private final Discounts discounts; + private final Gifts gifts; + + public Bill(Discounts discounts, Gifts gifts) { + this.discounts = discounts; + this.gifts = gifts; + } + + public int getTotalBenefit(Orders orders) { + return getAmount(this::sumBenefit, orders); + } + + public int getDiscountPrice(Orders orders) { + return orders.getTotalPrice() - discounts.sumDiscount(); + } + + public GiftsDto getGiftDto() { + return new GiftsDto(gifts.getResult()); + } + + public BenefitDto getBenefitDto() { + return new BenefitDto(discounts.getResult(), gifts.sumPrice()); + } + + public String getBadgeName() { + return Badge.getNameByBenefit(sumBenefit()); + } + + private int sumBenefit() { + return discounts.sumDiscount() + gifts.sumPrice(); + } + + private boolean isEventApplicable(Orders orders) { + return orders.getTotalPrice() >= MINIMUM_ORDERS_PRICE; + } + + private <T> int getAmount(Supplier<T> supplier, Orders orders) { + if (isEventApplicable(orders)) { + return (int) supplier.get(); + } + return EVENT_NOT_APPLIED_AMOUNT; + } +}
Java
์™€์šฐ ๋„๋ฉ”์ธ๊ณผ ์ฑ…์ž„๊ณผ ์—ญํ• ์— ๋Œ€ํ•ด์„œ ๊นŠ์€ ๊ณ ๋ฏผ์„ ํ•˜์‹  ๊ฒƒ์ด ๋А๊ปด์ง€๋„ค์š”.. ๐Ÿ‘๐Ÿป ๐Ÿ‘๐Ÿป ์ฑ…์ž„๊ณผ ์—ญํ• ์„ ๋ถ„๋ฆฌํ•˜๊ณ  ๋ถ€์—ฌํ•˜๋Š” ๊ฒƒ์€ ์ €๋„ ์ต์ˆ™์น˜๊ฐ€ ์•Š์€๋ฐ ์ •์„ฑ์Šค๋Ÿฌ์šด ๋‹ต๋ณ€ ์ฃผ์…”์„œ ์ €๋„ ์ €๋งŒ์˜ ๊ธฐ์ค€์„ ํ•œ๋ฒˆ ๊ฒ€ํ† ํ•ด๋ณด์•„์•ผ๊ฒ ๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“œ๋„ค์š” ๐Ÿ˜„
@@ -0,0 +1,55 @@ +package christmas.controller; + +import static christmas.utils.RepeatReader.repeatRead; + +import christmas.domain.Bill; +import christmas.domain.Orders; +import christmas.domain.Restaurant; +import christmas.domain.VisitDate; +import christmas.view.InputView; +import christmas.view.OutputView; + +public class EventController { + private final Restaurant restaurant; + private final InputView inputView; + private final OutputView outputView; + + public EventController(Restaurant restaurant, InputView inputView, OutputView outputView) { + this.restaurant = restaurant; + this.inputView = inputView; + this.outputView = outputView; + } + + public void run() { + VisitDate visitDate = repeatRead(this::readDate); + Orders orders = repeatRead(this::readOrders); + + Bill bill = restaurant.order(visitDate, orders); + + printOrders(orders); + printBill(bill, orders); + } + + private VisitDate readDate() { + int date = inputView.readDate(); + return new VisitDate(date); + } + + private Orders readOrders() { + String orders = inputView.readOrders(); + return new Orders(orders); + } + + private void printOrders(Orders orders) { + outputView.printOrders(orders.getOrders()); + outputView.printPrice(orders.getTotalPrice()); + } + + private void printBill(Bill bill, Orders orders) { + outputView.printGifts(bill.getGiftDto()); + outputView.printBenefit(bill.getBenefitDto()); + outputView.printBenefitAmount(bill.getTotalBenefit(orders)); + outputView.printDiscountPrice(bill.getDiscountPrice(orders)); + outputView.printBadge(bill.getBadgeName()); + } +}
Java
์šฐ์™€.. ์ „๋ฐ˜์ ์œผ๋กœ ์ฝ”๋“œ ํ๋ฆ„์ด ์ž˜ ์ฝํžˆ๋„ค์š”..!! ํ• ์ธ ๊ฒฐ๊ณผ๋ฅผ ๋ณด์—ฌ์ฃผ๋Š” ํ•จ์ˆ˜์˜ ์ด๋ฆ„์„ ์–ด๋–ป๊ฒŒ ํ•ด์•ผํ• ๊นŒ ๊ณ ๋ฏผ์„ ๋งŽ์ด ํ–ˆ๋Š”๋ฐ, printBill()์ด๋ผ๋Š” ์ด๋ฆ„์„ ๋ณด๋‹ˆ ๋จธ๋ฆฌ์— ๋ง์น˜๋ฅผ ํ•œ ๋Œ€ ๋งž์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.. ๐Ÿ‘
@@ -0,0 +1,84 @@ +import { Console } from '@woowacourse/mission-utils'; +import { PROMOTION_CATEGORIES } from '../constant/index.js'; + +const MESSAGE = { + GREETINGS: '์•ˆ๋…•ํ•˜์„ธ์š”! ์šฐํ…Œ์ฝ” ์‹๋‹น 12์›” ์ด๋ฒคํŠธ ํ”Œ๋ž˜๋„ˆ์ž…๋‹ˆ๋‹ค.', + INTRO_PREVIEW: '12์›” 26์ผ์— ์šฐํ…Œ์ฝ” ์‹๋‹น์—์„œ ๋ฐ›์„ ์ด๋ฒคํŠธ ํ˜œํƒ ๋ฏธ๋ฆฌ ๋ณด๊ธฐ!\n', + ORDER_MENU_TITLE: '<์ฃผ๋ฌธ ๋ฉ”๋‰ด>', + TOTAL_PRICE_WITHOUT_DISCOUNT_TITLE: '<ํ• ์ธ ์ „ ์ด์ฃผ๋ฌธ ๊ธˆ์•ก>', + BENEFIT_DETAILS_TITLE: '<ํ˜œํƒ ๋‚ด์—ญ>', + TOTAL_PRICE_WITH_DISCOUNT_TITLE: '<ํ• ์ธ ํ›„ ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก>', + GIFT_TITLE: '<์ฆ์ • ๋ฉ”๋‰ด>', + BENEFIT_TOTAL_PRICE_TITLE: '<์ดํ˜œํƒ ๊ธˆ์•ก>', + BADGE_TITLE: '<12์›” ์ด๋ฒคํŠธ ๋ฐฐ์ง€>', + NONE: '์—†์Œ', + MENU: (name, count) => `${name} ${count}๊ฐœ`, + PRICE: (price) => `${price.toLocaleString()}์›`, + GIFT: (name, count) => `${name} ${count}๊ฐœ`, + DISCOUNT: (name, price) => `${name} ํ• ์ธ: -${price.toLocaleString()}์›`, + TOTAL_BENEFIT_PRICE: (price) => (price > 0 ? `-${price.toLocaleString()}์›` : '0์›'), +}; + +const OutputView = { + printGreetings() { + Console.print(MESSAGE.GREETINGS); + }, + printPreviewMessage() { + Console.print(MESSAGE.INTRO_PREVIEW); + Console.print(''); + }, + printOrderMenus(orders) { + Console.print(MESSAGE.ORDER_MENU_TITLE); + + orders.forEach((order) => { + Console.print(MESSAGE.MENU(order.name, order.count)); + }); + + Console.print(''); + }, + printTotalPriceWithoutDiscount(totalPrice) { + Console.print(MESSAGE.TOTAL_PRICE_WITHOUT_DISCOUNT_TITLE); + Console.print(MESSAGE.PRICE(totalPrice)); + Console.print(''); + }, + printBenefitDetails(promotions) { + Console.print(MESSAGE.BENEFIT_DETAILS_TITLE); + + const printData = []; + + promotions.forEach((promotion) => { + const { NAME, promotionBenefitPrice } = promotion; + const isApplied = promotionBenefitPrice > 0; + if (isApplied) printData.push(MESSAGE.DISCOUNT(NAME, promotionBenefitPrice)); + }); + if (printData.length === 0) printData.push(MESSAGE.NONE); + + Console.print(printData.join('\n')); + Console.print(''); + }, + printTotalPriceWithDiscount(totalPriceWithDiscount) { + Console.print(MESSAGE.TOTAL_PRICE_WITH_DISCOUNT_TITLE); + Console.print(MESSAGE.PRICE(totalPriceWithDiscount)); + Console.print(''); + }, + printGiveWayMenu(promotions) { + const giftMenu = promotions.find((promotion) => promotion.EVENT === PROMOTION_CATEGORIES.GIFT); + const { PRODUCT, promotionBenefitPrice } = giftMenu; + const isApplied = promotionBenefitPrice > 0; + + Console.print(MESSAGE.GIFT_TITLE); + Console.print(isApplied ? MESSAGE.GIFT(PRODUCT.NAME, 1) : MESSAGE.NONE); + Console.print(''); + }, + printTotalBenefitPrice(totalBenefitPrice) { + Console.print(MESSAGE.BENEFIT_TOTAL_PRICE_TITLE); + Console.print(MESSAGE.TOTAL_BENEFIT_PRICE(totalBenefitPrice)); + Console.print(''); + }, + printBadge(badge) { + Console.print(MESSAGE.BADGE_TITLE); + Console.print(badge); + }, +}; + +export default OutputView;
JavaScript
์ €๋„ ์ด ๋ถ€๋ถ„ ์‹ค์ˆ˜ํ–ˆ๋Š”๋ฐ, ์ผ์ž๊ฐ€ ๋ฐ”๋€Œ์–ด์„œ ์ถœ๋ ฅ๋˜๋„๋ก ํ•ด์•ผํ•ด์š”..ใ…œใ…œ
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', + IS_INVALID_ORDER: '์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
Input์— ๋Œ€ํ•œ ๋ชจ๋“  ์œ ํšจ์„ฑ ๊ฒ€์ฆ์„ Order ๋„๋ฉ”์ธ์—์„œ ์ฒ˜๋ฆฌํ•˜๊ณ  ๊ณ„์‹ ๋ฐ ์ด๋ ‡๊ฒŒ ๊ตฌํ˜„ํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ด์š”. ๊ณตํ†ต ํ”ผ๋“œ๋ฐฑ์—์„œ ๊ตฌํ˜„ ์ˆœ์„œ์— ๋Œ€ํ•œ ์ด์•ผ๊ธฐ๊ฐ€ ์žˆ๋Š”๋ฐ, ์ด ํด๋ž˜์Šค๋Š” ํ•„๋“œ-์ƒ์„ฑ์ž-๋ฉ”์„œ๋“œ ์ˆœ์œผ๋กœ ๊ตฌํ˜„๋˜์–ด์žˆ์ง€ ์•Š์•„์„œ ์ด ๋ถ€๋ถ„์„ ๊ฐœ์„ ํ•ด์•ผ ํ•  ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', + IS_INVALID_ORDER: '์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
์ง€๊ธˆ ์ด menus๋Š” ์ƒ์ˆ˜ ๊ฐ์ฒด MENUS์ธ๋ฐ ๋‹ค์‹œ Map์œผ๋กœ ๋งŒ๋“œ์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ด์š”. MENUS์˜ ํ‚ค๊ฐ’์„ ํ™œ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ ๊ฐœ์„ ํ•˜์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', + IS_INVALID_ORDER: '์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
์ œ๊ฐ€ ์ž˜ ๋ชป ์ฐพ๋Š” ๊ฑด์ง€ ๋ชจ๋ฅด๊ฒ ๋Š”๋ฐ, ์ด orderDate๋Š” Order ๋„๋ฉ”์ธ ๋‚ด์—์„œ ์‚ฌ์šฉ๋˜๋Š” ๋กœ์ง์ด ์—†๋Š” ๊ฒƒ ๊ฐ™์•„์š”. ์—ญํ• ์„ ๋ถ„๋ฆฌํ•ด์•ผ ํ•  ๊ฒƒ ๊ฐ™๋‹ค๊ณ  ๋А๊ปด์ง€๋Š”๋ฐ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋Š”์ง€ ๊ถ๊ธˆํ•ด์š”..!
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', + IS_INVALID_ORDER: '์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
๋ฉ”์„œ๋“œ๋งˆ๋‹ค ๊ฐœํ–‰์„ ๋„ฃ์–ด์ฃผ์‹œ๋ฉด ๊ฐ€๋…์„ฑ์ด ๋†’์•„์งˆ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -1,5 +1,42 @@ +import { InputView, OutputView } from './view/index.js'; +import { MENUS, PROMOTION_MONTH, PROMOTION_YEAR } from './constant/index.js'; +import { Order, Planner, PromotionCalendar, Promotions } from './model/index.js'; + class App { - async run() {} + async run() { + OutputView.printGreetings(); + const { order, planner } = await this.reserve(); + OutputView.printPreviewMessage(); + await this.preview(order, planner); + } + + async reserve() { + const orderDate = await InputView.readOrderDate((input) => Order.validateDate(input)); + const orderMenu = await InputView.readOrderMenus((input) => Order.validateOrder(input)); + const order = new Order(MENUS, orderMenu, orderDate); + const planner = new Planner(order, new PromotionCalendar(PROMOTION_YEAR, PROMOTION_MONTH, Promotions)); + + return { + order, + planner, + }; + } + + async preview(order, planner) { + const orderMenuList = order.getOrderMenuList(); + const totalPriceWithoutDiscount = order.getTotalPrice(); + const promotions = planner.getPromotionsByOrderDate(); + const totalBenefitPrice = planner.getTotalBenefitPrice(); + const totalPriceWithDiscount = planner.getTotalPriceWithDiscount(); + const badge = planner.getBadge(); + OutputView.printOrderMenus(orderMenuList); + OutputView.printTotalPriceWithoutDiscount(totalPriceWithoutDiscount); + OutputView.printGiveWayMenu(promotions); + OutputView.printBenefitDetails(promotions); + OutputView.printTotalBenefitPrice(totalBenefitPrice); + OutputView.printTotalPriceWithDiscount(totalPriceWithDiscount); + OutputView.printBadge(badge); + } } export default App;
JavaScript
์ง€๊ทนํžˆ ๊ฐœ์ธ์ ์ธ ์˜๊ฒฌ์ธ๋ฐ, ๋ฉ”์„œ๋“œ๋ช…์„ '์˜ˆ์•ฝ'์ด๋ผ๊ณ  ์ง€์œผ์…จ๋Š”๋ฐ oderDate๋Š” ์กฐ๊ธˆ ํ˜ผ๋ž€์„ ์ค„ ์ˆ˜ ์žˆ๋Š” ๊ฒƒ ๊ฐ™์•„์š”. '๋ฐฉ๋ฌธ'์ด๋‚˜ '์˜ˆ์•ฝ'์œผ๋กœ ๋ณ€๊ฒฝํ•˜์‹œ๋Š” ๊ฒŒ ์–ด๋–จ๊นŒ์š”..?
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', + IS_INVALID_ORDER: '์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
์•„ static method๋ผ ์œ„๋กœ ๋บด๋†จ์Šต๋‹ˆ๋‹ค. static์€ ๊ฐ ๊ฐ์ฒด๋งˆ๋‹ค์˜ ๋ฐ์ดํ„ฐ์— ์ ‘๊ทผํ•  ์ˆ˜ ์—†๊ณ  ํ•จ์ˆ˜๋กœ์„œ์˜ ๊ธฐ๋Šฅ๋งŒ ๊ฐ€๋Šฅํ•ด์„œ ์œ„๋กœ ๋บด๋†จ์Šต๋‹ˆ๋‹ค. ๋”ฐ๋กœ Validation ๋นผ๊ธฐ์—๋Š” ๋ชจ๋‘ ์˜ˆ์•ฝ๊ด€์ ์—์„œ ์œ ํšจ์„ฑ ๊ฒ€์ฆ์ด๋ผ Order์— ๋ชจ๋‘ ๋„ฃ์—ˆ์Šต๋‹ˆ๋‹ค. view์—์„œ ๋”ฐ๋กœ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ๋„ ์žˆ์—ˆ๋Š”๋ฐ ์˜ˆ์•ฝ์— ๊ด€๋ จ๋œ ๊ฒ€์ฆ์ด๋ผ๊ณ  ํ‘œํ˜„ํ•˜๊ณ  ์‹ถ์—ˆ์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,84 @@ +import { Console } from '@woowacourse/mission-utils'; +import { PROMOTION_CATEGORIES } from '../constant/index.js'; + +const MESSAGE = { + GREETINGS: '์•ˆ๋…•ํ•˜์„ธ์š”! ์šฐํ…Œ์ฝ” ์‹๋‹น 12์›” ์ด๋ฒคํŠธ ํ”Œ๋ž˜๋„ˆ์ž…๋‹ˆ๋‹ค.', + INTRO_PREVIEW: '12์›” 26์ผ์— ์šฐํ…Œ์ฝ” ์‹๋‹น์—์„œ ๋ฐ›์„ ์ด๋ฒคํŠธ ํ˜œํƒ ๋ฏธ๋ฆฌ ๋ณด๊ธฐ!\n', + ORDER_MENU_TITLE: '<์ฃผ๋ฌธ ๋ฉ”๋‰ด>', + TOTAL_PRICE_WITHOUT_DISCOUNT_TITLE: '<ํ• ์ธ ์ „ ์ด์ฃผ๋ฌธ ๊ธˆ์•ก>', + BENEFIT_DETAILS_TITLE: '<ํ˜œํƒ ๋‚ด์—ญ>', + TOTAL_PRICE_WITH_DISCOUNT_TITLE: '<ํ• ์ธ ํ›„ ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก>', + GIFT_TITLE: '<์ฆ์ • ๋ฉ”๋‰ด>', + BENEFIT_TOTAL_PRICE_TITLE: '<์ดํ˜œํƒ ๊ธˆ์•ก>', + BADGE_TITLE: '<12์›” ์ด๋ฒคํŠธ ๋ฐฐ์ง€>', + NONE: '์—†์Œ', + MENU: (name, count) => `${name} ${count}๊ฐœ`, + PRICE: (price) => `${price.toLocaleString()}์›`, + GIFT: (name, count) => `${name} ${count}๊ฐœ`, + DISCOUNT: (name, price) => `${name} ํ• ์ธ: -${price.toLocaleString()}์›`, + TOTAL_BENEFIT_PRICE: (price) => (price > 0 ? `-${price.toLocaleString()}์›` : '0์›'), +}; + +const OutputView = { + printGreetings() { + Console.print(MESSAGE.GREETINGS); + }, + printPreviewMessage() { + Console.print(MESSAGE.INTRO_PREVIEW); + Console.print(''); + }, + printOrderMenus(orders) { + Console.print(MESSAGE.ORDER_MENU_TITLE); + + orders.forEach((order) => { + Console.print(MESSAGE.MENU(order.name, order.count)); + }); + + Console.print(''); + }, + printTotalPriceWithoutDiscount(totalPrice) { + Console.print(MESSAGE.TOTAL_PRICE_WITHOUT_DISCOUNT_TITLE); + Console.print(MESSAGE.PRICE(totalPrice)); + Console.print(''); + }, + printBenefitDetails(promotions) { + Console.print(MESSAGE.BENEFIT_DETAILS_TITLE); + + const printData = []; + + promotions.forEach((promotion) => { + const { NAME, promotionBenefitPrice } = promotion; + const isApplied = promotionBenefitPrice > 0; + if (isApplied) printData.push(MESSAGE.DISCOUNT(NAME, promotionBenefitPrice)); + }); + if (printData.length === 0) printData.push(MESSAGE.NONE); + + Console.print(printData.join('\n')); + Console.print(''); + }, + printTotalPriceWithDiscount(totalPriceWithDiscount) { + Console.print(MESSAGE.TOTAL_PRICE_WITH_DISCOUNT_TITLE); + Console.print(MESSAGE.PRICE(totalPriceWithDiscount)); + Console.print(''); + }, + printGiveWayMenu(promotions) { + const giftMenu = promotions.find((promotion) => promotion.EVENT === PROMOTION_CATEGORIES.GIFT); + const { PRODUCT, promotionBenefitPrice } = giftMenu; + const isApplied = promotionBenefitPrice > 0; + + Console.print(MESSAGE.GIFT_TITLE); + Console.print(isApplied ? MESSAGE.GIFT(PRODUCT.NAME, 1) : MESSAGE.NONE); + Console.print(''); + }, + printTotalBenefitPrice(totalBenefitPrice) { + Console.print(MESSAGE.BENEFIT_TOTAL_PRICE_TITLE); + Console.print(MESSAGE.TOTAL_BENEFIT_PRICE(totalBenefitPrice)); + Console.print(''); + }, + printBadge(badge) { + Console.print(MESSAGE.BADGE_TITLE); + Console.print(badge); + }, +}; + +export default OutputView;
JavaScript
์œผ์•„ ๊ทธ๋Ÿฌ๋„ค์š” ใ… ใ… ใ…  ์ƒ๊ฐ์ง€๋„ ๋ชปํ–ˆ๋„ค์š” ใ… ใ… 
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', + IS_INVALID_ORDER: '์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
์—ญํ• ์„ ๋ถ„๋ฆฌํ•œ๋‹ค๋Š” ๋ง์”€์ด ์–ด๋–ค๊ฑด์ง€ ์ž˜ ์ดํ•ด๊ฐ€ ์•ˆ๋˜๋Š”๋ฐ ํ˜น์‹œ ์–ด๋–ค ๋ง์”€์ด์‹ ์ง€ ์•Œ๋ ค์ฃผ์‹ค ์ˆ˜ ์žˆ์œผ์‹ค๊นŒ์š”? getOrderDate๋Š” Promotion์—์„œ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', + IS_INVALID_ORDER: '์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
๋„ต.... ์ œ๊ฐ€ ๋ด๋„ ์ข€ ๊ฐ€๋…์„ฑ์ด ๋–จ์–ด์ง€๋Š” ๊ฒƒ ๊ฐ™๋„ค์š”
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', + IS_INVALID_ORDER: '์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
```js const validators = [ Order.validateDuplicationOrder.bind(this, orderMenus) // ... ] ``` ์œ„์™€ ๊ฐ™์ด `bind` ์‚ฌ์šฉ๋„ ๊ณ ๋ คํ•ด๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -1,5 +1,42 @@ +import { InputView, OutputView } from './view/index.js'; +import { MENUS, PROMOTION_MONTH, PROMOTION_YEAR } from './constant/index.js'; +import { Order, Planner, PromotionCalendar, Promotions } from './model/index.js'; + class App { - async run() {} + async run() { + OutputView.printGreetings(); + const { order, planner } = await this.reserve(); + OutputView.printPreviewMessage(); + await this.preview(order, planner); + } + + async reserve() { + const orderDate = await InputView.readOrderDate((input) => Order.validateDate(input)); + const orderMenu = await InputView.readOrderMenus((input) => Order.validateOrder(input)); + const order = new Order(MENUS, orderMenu, orderDate); + const planner = new Planner(order, new PromotionCalendar(PROMOTION_YEAR, PROMOTION_MONTH, Promotions)); + + return { + order, + planner, + }; + } + + async preview(order, planner) { + const orderMenuList = order.getOrderMenuList(); + const totalPriceWithoutDiscount = order.getTotalPrice(); + const promotions = planner.getPromotionsByOrderDate(); + const totalBenefitPrice = planner.getTotalBenefitPrice(); + const totalPriceWithDiscount = planner.getTotalPriceWithDiscount(); + const badge = planner.getBadge(); + OutputView.printOrderMenus(orderMenuList); + OutputView.printTotalPriceWithoutDiscount(totalPriceWithoutDiscount); + OutputView.printGiveWayMenu(promotions); + OutputView.printBenefitDetails(promotions); + OutputView.printTotalBenefitPrice(totalBenefitPrice); + OutputView.printTotalPriceWithDiscount(totalPriceWithDiscount); + OutputView.printBadge(badge); + } } export default App;
JavaScript
์•„ ๋งž๋„ค์š” ๊ทธ๊ฒŒ ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค
@@ -1,5 +1,42 @@ +import { InputView, OutputView } from './view/index.js'; +import { MENUS, PROMOTION_MONTH, PROMOTION_YEAR } from './constant/index.js'; +import { Order, Planner, PromotionCalendar, Promotions } from './model/index.js'; + class App { - async run() {} + async run() { + OutputView.printGreetings(); + const { order, planner } = await this.reserve(); + OutputView.printPreviewMessage(); + await this.preview(order, planner); + } + + async reserve() { + const orderDate = await InputView.readOrderDate((input) => Order.validateDate(input)); + const orderMenu = await InputView.readOrderMenus((input) => Order.validateOrder(input)); + const order = new Order(MENUS, orderMenu, orderDate); + const planner = new Planner(order, new PromotionCalendar(PROMOTION_YEAR, PROMOTION_MONTH, Promotions)); + + return { + order, + planner, + }; + } + + async preview(order, planner) { + const orderMenuList = order.getOrderMenuList(); + const totalPriceWithoutDiscount = order.getTotalPrice(); + const promotions = planner.getPromotionsByOrderDate(); + const totalBenefitPrice = planner.getTotalBenefitPrice(); + const totalPriceWithDiscount = planner.getTotalPriceWithDiscount(); + const badge = planner.getBadge(); + OutputView.printOrderMenus(orderMenuList); + OutputView.printTotalPriceWithoutDiscount(totalPriceWithoutDiscount); + OutputView.printGiveWayMenu(promotions); + OutputView.printBenefitDetails(promotions); + OutputView.printTotalBenefitPrice(totalBenefitPrice); + OutputView.printTotalPriceWithDiscount(totalPriceWithDiscount); + OutputView.printBadge(badge); + } } export default App;
JavaScript
์ง„์ž…์  ์ฝ”๋“œ์—์„œ ์ „์ฒด์ ์ธ ํ๋ฆ„ ํŒŒ์•…์ด ์–ด๋ ต๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“ญ๋‹ˆ๋‹ค. `printPreviewMessage()`, `this.preview` ํ•จ์ˆ˜๋“ค์ด ๋ฌด์Šจ ์ผ์„ ํ•˜๋Š”์ง€ ์ž˜ ์˜ˆ์ƒ์ด ์•ˆ ๊ฐ€์š”.
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', + IS_INVALID_ORDER: '์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
์•„ ์ถ”ํ›„ ๋‹ค๋ฅธ ๋ฉ”๋‰ด๋ฅผ ๋„ฃ์„ ๋•Œ๋„ ์žฌ์‚ฌ์šฉ์„ฑ์„ ์ƒ๊ฐํ•ด์„œ ๋”ฐ๋กœ ๋„ฃ์–ด๋†จ์Šต๋‹ˆ๋‹ค. Map์„ ์‚ฌ์šฉํ•œ ์ด์œ ๋Š” ์ €๋Š” ์ตœ๋Œ€ํ•œ Object[Key] ๋กœ ์‚ฌ์šฉ์„ ์ž์ œ ํ• ๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค Map์œผ๋กœ ๋งŒ๋“ค๋ฉด get(),set()๋„ ํŽธํ•˜๊ณ  forEach๋‚˜ ๋‹ค์–‘ํ•œ ํ•จ์ˆ˜๋„ ํ•œ ๋ฒˆ์— ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์–ด์„œ ์ข€ ๋” ์ข‹์€ ๊ฒƒ ๊ฐ™๋”๋ผ๊ตฌ์š”
@@ -0,0 +1,55 @@ +import { BADGE, PROMOTION_CATEGORIES, PROMOTION_MINIMUM_PRICE } from '../constant/index.js'; + +class Planner { + #order; + #calendar; + + constructor(order, calendar) { + this.#order = order; + this.#calendar = calendar; + } + + getPromotionsByOrderDate() { + const promotions = this.#calendar.getPromotionsByDate(this.#order.getOrderDate()); + const activePromotions = []; + promotions.forEach((promotion) => { + const { CONFIG } = promotion; + activePromotions.push({ + ...CONFIG, + promotionBenefitPrice: this.#applyPromotions(promotion), + }); + }); + + return activePromotions; + } + getTotalBenefitPrice() { + const promotions = this.getPromotionsByOrderDate(); + + return promotions.reduce((acc, cur) => acc + cur.promotionBenefitPrice, 0); + } + getTotalPriceWithDiscount() { + const promotions = this.getPromotionsByOrderDate(); + const totalPrice = this.#order.getTotalPrice(); + const getTotalBenefitPrice = this.getTotalBenefitPrice(); + const giftPromotion = promotions.find((promotion) => promotion.EVENT === PROMOTION_CATEGORIES.GIFT); + + return totalPrice - (getTotalBenefitPrice - giftPromotion.promotionBenefitPrice); + } + getBadge() { + const { SANTA, TREE, STAR, NONE } = BADGE; + const totalBenefitPrice = this.getTotalBenefitPrice(); + if (totalBenefitPrice >= SANTA.PRICE) return SANTA.NAME; + if (totalBenefitPrice >= TREE.PRICE) return TREE.NAME; + if (totalBenefitPrice >= STAR.PRICE) return STAR.NAME; + + return NONE.NAME; + } + #applyPromotions(promotion) { + const totalPriceWithoutDiscount = this.#order.getTotalPrice(); + if (totalPriceWithoutDiscount < PROMOTION_MINIMUM_PRICE) return 0; + + return promotion.getPromotionPrice(this.#order); + } +} + +export default Planner;
JavaScript
Planner๊ฐ€ ๋„ˆ๋ฌด ๋งŽ์€ ๊ฐ์ฒด์— ์˜์กดํ•˜๋Š” ๊ฒƒ ๊ฐ™์•„์š”. ๋˜, ์–ด๋–ค ๊ฐ์ฒด์ธ์ง€ ์ž˜ ํŒŒ์•…์ด ์•ˆ ๋ผ์š”. Planner ๋ผ๋Š” ์ด๋ฆ„๊ณผ, ๋ฉ”์„œ๋“œ๊ฐ€ ๋งค์นญ์ด ์ž˜ ์•ˆ๋˜๋„ค์š”
@@ -0,0 +1,45 @@ +import { PROMOTIONS } from '../constant/index.js'; + +const ChristPromotion = { + CONFIG: PROMOTIONS.CHRISTMAS, + getPromotionPrice(order) { + const date = order.getOrderDate(); + + return this.CONFIG.BENEFIT_PRICE + this.CONFIG.BENEFIT_PRICE * 0.1 * (date - 1); + }, +}; +const WeekendsPromotion = { + CONFIG: PROMOTIONS.WEEKENDS, + getPromotionPrice(order) { + const productInOrder = order.getOrderMenuByCategory(this.CONFIG.PRODUCT); + const menuCount = productInOrder.reduce((acc, cur) => acc + Number(cur.count), 0); + + return this.CONFIG.BENEFIT_PRICE * menuCount; + }, +}; +const WeekdaysPromotion = { + CONFIG: PROMOTIONS.WEEKDAYS, + getPromotionPrice(order) { + const productInOrder = order.getOrderMenuByCategory(this.CONFIG.PRODUCT); + const menuCount = productInOrder.reduce((acc, cur) => acc + Number(cur.count), 0); + + return this.CONFIG.BENEFIT_PRICE * menuCount; + }, +}; +const SpecialPromotion = { + CONFIG: PROMOTIONS.SPECIAL, + getPromotionPrice() { + return this.CONFIG.BENEFIT_PRICE; + }, +}; +const GiftPromotion = { + CONFIG: PROMOTIONS.GIFT, + getPromotionPrice(order) { + const preDiscountAmount = order.getTotalPrice(); + if (preDiscountAmount < this.CONFIG.MINIMUM_PRICE) return 0; + + return this.CONFIG.BENEFIT_PRICE; + }, +}; +export const Promotions = [ChristPromotion, WeekendsPromotion, WeekdaysPromotion, SpecialPromotion, GiftPromotion]; +export default Promotions;
JavaScript
`CONFIG`๊ฐ€ ๋ญ˜ ๋œปํ•˜๋Š”์ง€ ์ถ”์ธก์ด ์ž˜ ์•ˆ๋˜๋„ค์š”. ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ `PROMOTIONS.CHRISTMAS`์— ๋ญ๊ฐ€ ๋“ค์–ด์žˆ๋Š”์ง€ ์˜ˆ์ƒ์ด ์•ˆ๊ฐ€์š”. ์ƒ์ˆ˜๋“ค์„ ์กฐ๊ธˆ๋” ๋‹จ์ˆœํ™”ํ•˜๋Š”๊ฒŒ ํ•„์š”ํ•˜๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,13 @@ +const PREFIX_ERROR = '[ERROR]'; + +export const check = (errorMessage, validator) => { + if (validator()) throw new Error(`${PREFIX_ERROR} ${errorMessage}`); +}; +export const isMoreThanLimit = (errorMessage, target, limit) => check(errorMessage, () => target > limit); +export const isDuplicate = (errorMessage, targets) => + check(errorMessage, () => new Set(targets).size !== targets.length); +export const isNotMatchRegex = (errorMessage, target, regex) => check(errorMessage, () => !regex.test(target)); +export const isEveryInclude = (errorMessage, targets, references) => + check(errorMessage, () => targets.every((item) => references.includes(item))); +export const isSomeNotInclude = (errorMessage, targets, references) => + check(errorMessage, () => targets.some((item) => !references.includes(item)));
JavaScript
constant ํด๋”๋กœ ๋”ฐ๋กœ ๋ถ„๋ฆฌํ•˜ํ•˜์ง€ ์•Š๊ณ  ์—ฌ๊ธฐ์„œ ์„ ์–ธํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ๋‚˜์š”?
@@ -0,0 +1,84 @@ +import { Console } from '@woowacourse/mission-utils'; +import { PROMOTION_CATEGORIES } from '../constant/index.js'; + +const MESSAGE = { + GREETINGS: '์•ˆ๋…•ํ•˜์„ธ์š”! ์šฐํ…Œ์ฝ” ์‹๋‹น 12์›” ์ด๋ฒคํŠธ ํ”Œ๋ž˜๋„ˆ์ž…๋‹ˆ๋‹ค.', + INTRO_PREVIEW: '12์›” 26์ผ์— ์šฐํ…Œ์ฝ” ์‹๋‹น์—์„œ ๋ฐ›์„ ์ด๋ฒคํŠธ ํ˜œํƒ ๋ฏธ๋ฆฌ ๋ณด๊ธฐ!\n', + ORDER_MENU_TITLE: '<์ฃผ๋ฌธ ๋ฉ”๋‰ด>', + TOTAL_PRICE_WITHOUT_DISCOUNT_TITLE: '<ํ• ์ธ ์ „ ์ด์ฃผ๋ฌธ ๊ธˆ์•ก>', + BENEFIT_DETAILS_TITLE: '<ํ˜œํƒ ๋‚ด์—ญ>', + TOTAL_PRICE_WITH_DISCOUNT_TITLE: '<ํ• ์ธ ํ›„ ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก>', + GIFT_TITLE: '<์ฆ์ • ๋ฉ”๋‰ด>', + BENEFIT_TOTAL_PRICE_TITLE: '<์ดํ˜œํƒ ๊ธˆ์•ก>', + BADGE_TITLE: '<12์›” ์ด๋ฒคํŠธ ๋ฐฐ์ง€>', + NONE: '์—†์Œ', + MENU: (name, count) => `${name} ${count}๊ฐœ`, + PRICE: (price) => `${price.toLocaleString()}์›`, + GIFT: (name, count) => `${name} ${count}๊ฐœ`, + DISCOUNT: (name, price) => `${name} ํ• ์ธ: -${price.toLocaleString()}์›`, + TOTAL_BENEFIT_PRICE: (price) => (price > 0 ? `-${price.toLocaleString()}์›` : '0์›'), +}; + +const OutputView = { + printGreetings() { + Console.print(MESSAGE.GREETINGS); + }, + printPreviewMessage() { + Console.print(MESSAGE.INTRO_PREVIEW); + Console.print(''); + }, + printOrderMenus(orders) { + Console.print(MESSAGE.ORDER_MENU_TITLE); + + orders.forEach((order) => { + Console.print(MESSAGE.MENU(order.name, order.count)); + }); + + Console.print(''); + }, + printTotalPriceWithoutDiscount(totalPrice) { + Console.print(MESSAGE.TOTAL_PRICE_WITHOUT_DISCOUNT_TITLE); + Console.print(MESSAGE.PRICE(totalPrice)); + Console.print(''); + }, + printBenefitDetails(promotions) { + Console.print(MESSAGE.BENEFIT_DETAILS_TITLE); + + const printData = []; + + promotions.forEach((promotion) => { + const { NAME, promotionBenefitPrice } = promotion; + const isApplied = promotionBenefitPrice > 0; + if (isApplied) printData.push(MESSAGE.DISCOUNT(NAME, promotionBenefitPrice)); + }); + if (printData.length === 0) printData.push(MESSAGE.NONE); + + Console.print(printData.join('\n')); + Console.print(''); + }, + printTotalPriceWithDiscount(totalPriceWithDiscount) { + Console.print(MESSAGE.TOTAL_PRICE_WITH_DISCOUNT_TITLE); + Console.print(MESSAGE.PRICE(totalPriceWithDiscount)); + Console.print(''); + }, + printGiveWayMenu(promotions) { + const giftMenu = promotions.find((promotion) => promotion.EVENT === PROMOTION_CATEGORIES.GIFT); + const { PRODUCT, promotionBenefitPrice } = giftMenu; + const isApplied = promotionBenefitPrice > 0; + + Console.print(MESSAGE.GIFT_TITLE); + Console.print(isApplied ? MESSAGE.GIFT(PRODUCT.NAME, 1) : MESSAGE.NONE); + Console.print(''); + }, + printTotalBenefitPrice(totalBenefitPrice) { + Console.print(MESSAGE.BENEFIT_TOTAL_PRICE_TITLE); + Console.print(MESSAGE.TOTAL_BENEFIT_PRICE(totalBenefitPrice)); + Console.print(''); + }, + printBadge(badge) { + Console.print(MESSAGE.BADGE_TITLE); + Console.print(badge); + }, +}; + +export default OutputView;
JavaScript
airbnb ๊ทœ์น™์—์„œ key๊ฐ’์€ ์†Œ๋ฌธ์ž๋กœ ํ•˜๋Š”๊ฒƒ์„ ๊ถŒ์žฅํ•˜๊ณ  ์žˆ์–ด์š”.
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', + IS_INVALID_ORDER: '์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
ใ…‡ใ…~ static ๋ฉ”์„œ๋“œ๋Š” ์œ„๋กœ ๋นผ๋†“์•„๋„ ๋˜๋Š”๊ตฐ์š”.. ์ฒ˜์Œ ์•Œ์•˜๋„ค์š”..!
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', + IS_INVALID_ORDER: '์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
์ €๋„ ๋ช…ํ™•ํ•˜๊ฒŒ ์„ค๋ช…๋“œ๋ฆด ์ˆ˜ ์žˆ์„์ง€ ๋ชจ๋ฅด๊ฒ ๋Š”๋ฐ, Order๋ผ๋Š” ๋„๋ฉ”์ธ์˜ ์ƒํƒœ๊ฐ’์œผ๋กœ orderDate๋ฅผ ๊ฐ–๋Š”๋ฐ Order ๋„๋ฉ”์ธ ๋‚ด๋ถ€์—์„œ ์‚ฌ์šฉ๋˜์ง€ ์•Š๊ณ  Promotion์—์„œ๋งŒ ์‚ฌ์šฉ๋œ๋‹ค๋ฉด Promotion ๋„๋ฉ”์ธ์— ํ•„์š”ํ•œ ๊ฐ’์ด์ง€ ์•Š์„๊นŒ ์ƒ๊ฐ์ด ๋“ค์—ˆ์–ด์š”.
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', + IS_INVALID_ORDER: '์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
์˜›๋‚ ์— bind๋ฅผ ์‚ฌ์šฉํ–ˆ๋‹ค๊ฐ€ ์ตœ๋Œ€ํ•œ "bind๋ž‘ apply๋Š” ์‚ฌ์šฉํ•˜์ง€ ๋งˆ๋ผ"๋ผ๊ณ  ํ•œ ์†Œ๋ฆฌ๋ฅผ ๋“ค์–ด์„œ.. ์ž˜ ์‚ฌ์šฉ์•ˆํ•˜๊ฒŒ ๋˜๋„ค์š”..์ด ๋ถ€๋ถ„์€ bind๋กœ ์‚ฌ์šฉํ•˜๋Š”๊ฒŒ ๊น”๋”ํ•  ๊ฒƒ ๊ฐ™๋„ค์š”. ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', + IS_INVALID_ORDER: '์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
ํ˜น์‹œ bind, apply ์ง€์–‘ ์ด์œ ๊ฐ€ ๋ญ”๊ฐ€์š”??
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', + IS_INVALID_ORDER: '์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
์—ฌ๊ธฐ์„œ๋Š” ๊ฐ์ฒด ๋™๊ฒฐ์„ ํ•ด์ฃผ์‹œ๋Š”๋ฐ ์ƒ์ˆ˜ ๊ฐ์ฒด๋Š” ๋™๊ฒฐ์„ ์•ˆ ํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์œผ์‹ค๊นŒ์š”? ์ €๋„ ์ด ๋ถ€๋ถ„์ด ๊ณ ๋ฏผ์ด๋ผ ์—ฌ์ญค๋ด์š”.
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', + IS_INVALID_ORDER: '์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
๊ตฌ์กฐ๋ถ„ํ•ดํ• ๋‹น์„ ์ž˜ ์“ฐ์‹œ๋Š” ๊ฒƒ ๊ฐ™์•„์š”! ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹น
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', + IS_INVALID_ORDER: '์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
Object[Key] ์‚ฌ์šฉ์„ ์ž์ œํ•˜์‹œ๋ ค๋Š” ์ด์œ ๊ฐ€ ์žˆ์œผ์‹ค๊นŒ์š”?
@@ -0,0 +1,126 @@ +import { isDuplicate, isEveryInclude, isMoreThanLimit, isNotMatchRegex, isSomeNotInclude } from '../util/index.js'; +import { LIMIT_ORDER_COUNT, MENU_CATEGORIES, MENUS, ORDER_REGEX } from '../constant/index.js'; + +const ERROR_MESSAGE = Object.freeze({ + INVALID_DATE: '์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', + IS_INVALID_ORDER: '์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.', +}); + +const { INVALID_DATE, IS_INVALID_ORDER } = ERROR_MESSAGE; + +class Order { + static validateOrder(orderMenus) { + const validators = [ + () => Order.validateDuplicationOrder(orderMenus), + () => Order.validateOrderMenuFormat(orderMenus, ORDER_REGEX.ORDER_FORMAT), + () => Order.validateLimitOrderCount(orderMenus, LIMIT_ORDER_COUNT), + () => Order.validateIncludeMenu(orderMenus, MENUS), + () => Order.validateOrderOnlyOneCategory(orderMenus, MENUS, MENU_CATEGORIES.BEVERAGE), + ]; + + validators.forEach((validator) => validator()); + } + static validateDate(date) { + const validators = [() => Order.validateDayFormat(date, ORDER_REGEX.DAY_FORMAT)]; + + validators.forEach((validator) => validator()); + } + static validateOrderOnlyOneCategory(orderMenus, menus, category) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameListForCategory = Object.values(menus) + .filter((menu) => menu.CATEGORY === category) + .map((menu) => menu.NAME); + + isEveryInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameListForCategory); + } + static validateIncludeMenu(orderMenus, menus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + const menuNameList = Object.values(menus).map((menu) => menu.NAME); + + isSomeNotInclude(IS_INVALID_ORDER, orderMenuNameList, menuNameList); + } + static validateDuplicationOrder(orderMenus) { + const { orderMenuNameList } = Order.parseOrders(orderMenus); + + isDuplicate(IS_INVALID_ORDER, orderMenuNameList); + } + static validateLimitOrderCount(orderMenus, limitOrderCount) { + const { totalOrderCount } = Order.parseOrders(orderMenus); + + isMoreThanLimit(IS_INVALID_ORDER, totalOrderCount, limitOrderCount); + } + static validateOrderMenuFormat(orderMenus, regex) { + const { orderMenuList } = Order.parseOrders(orderMenus); + + orderMenuList.forEach((orderMenu) => isNotMatchRegex(IS_INVALID_ORDER, orderMenu, regex)); + } + static validateDayFormat(date, regex) { + isNotMatchRegex(INVALID_DATE, date, regex); + } + static parseOrders(orderMenu) { + const orderMenuList = orderMenu.split(',').map((menu) => menu.trim()); + const orderMenuNameList = orderMenuList.map((menu) => menu.split('-')[0]); + const orderMenuCountList = orderMenuList.map((menu) => menu.split('-')[1]); + const totalOrderCount = orderMenuCountList.reduce((acc, cur) => acc + Number(cur), 0); + + return { + orderMenuList, + orderMenuNameList, + orderMenuCountList, + totalOrderCount, + }; + } + + #orderDate; + #orderMenus = new Map(); + #menus = new Map(); + + constructor(menus, orderMenus, orderDate) { + this.#menus = new Map(Object.entries(menus)); + this.#orderDate = orderDate; + this.#setOrderMenus(orderMenus); + } + + getOrderMenuList() { + return this.#getOrderMenuCategories() + .map((categoryName) => this.getOrderMenuByCategory(categoryName)) + .flat(); + } + getTotalPrice() { + return Array.from(this.#orderMenus.values()).reduce((acc, orderMenu) => { + const key = this.#getKeyByMenuName(orderMenu.name); + const menu = this.#menus.get(key); + return acc + menu.PRICE * orderMenu.count; + }, 0); + } + getOrderDate() { + return this.#orderDate; + } + getOrderMenuByCategory(categoryName) { + return Array.from(this.#orderMenus.values()).filter((orderMenu) => orderMenu.category === categoryName); + } + #setOrderMenus(orderMenus) { + const { orderMenuNameList, orderMenuCountList } = Order.parseOrders(orderMenus); + + orderMenuNameList.forEach((menuName, index) => { + const category = this.#getCategoryByMenuName(menuName); + const key = this.#getKeyByMenuName(menuName); + + this.#orderMenus.set(key, { + name: menuName, + count: orderMenuCountList[index], + category, + }); + }); + } + #getOrderMenuCategories() { + return Array.from(new Set(Array.from(this.#menus.values()).map((menu) => menu.CATEGORY))); + } + #getCategoryByMenuName(menuName) { + return Array.from(this.#menus.values()).find((menuMap) => menuMap.NAME === menuName).CATEGORY; + } + #getKeyByMenuName(menuName) { + return Array.from(this.#menus.keys()).find((key) => this.#menus.get(key).NAME === menuName); + } +} +export default Order;
JavaScript
๋ฐฐ์—ด, Map, ๊ฐ์ฒด์˜ ์—ฌ๋Ÿฌ๊ฐ€์ง€ ๋ฉ”์„œ๋“œ๋“ค์„ ์ž˜ ํ™œ์šฉํ•˜์‹œ๋Š” ๊ฒƒ ๊ฐ™์•„์š”. ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค!
@@ -0,0 +1,55 @@ +import { BADGE, PROMOTION_CATEGORIES, PROMOTION_MINIMUM_PRICE } from '../constant/index.js'; + +class Planner { + #order; + #calendar; + + constructor(order, calendar) { + this.#order = order; + this.#calendar = calendar; + } + + getPromotionsByOrderDate() { + const promotions = this.#calendar.getPromotionsByDate(this.#order.getOrderDate()); + const activePromotions = []; + promotions.forEach((promotion) => { + const { CONFIG } = promotion; + activePromotions.push({ + ...CONFIG, + promotionBenefitPrice: this.#applyPromotions(promotion), + }); + }); + + return activePromotions; + } + getTotalBenefitPrice() { + const promotions = this.getPromotionsByOrderDate(); + + return promotions.reduce((acc, cur) => acc + cur.promotionBenefitPrice, 0); + } + getTotalPriceWithDiscount() { + const promotions = this.getPromotionsByOrderDate(); + const totalPrice = this.#order.getTotalPrice(); + const getTotalBenefitPrice = this.getTotalBenefitPrice(); + const giftPromotion = promotions.find((promotion) => promotion.EVENT === PROMOTION_CATEGORIES.GIFT); + + return totalPrice - (getTotalBenefitPrice - giftPromotion.promotionBenefitPrice); + } + getBadge() { + const { SANTA, TREE, STAR, NONE } = BADGE; + const totalBenefitPrice = this.getTotalBenefitPrice(); + if (totalBenefitPrice >= SANTA.PRICE) return SANTA.NAME; + if (totalBenefitPrice >= TREE.PRICE) return TREE.NAME; + if (totalBenefitPrice >= STAR.PRICE) return STAR.NAME; + + return NONE.NAME; + } + #applyPromotions(promotion) { + const totalPriceWithoutDiscount = this.#order.getTotalPrice(); + if (totalPriceWithoutDiscount < PROMOTION_MINIMUM_PRICE) return 0; + + return promotion.getPromotionPrice(this.#order); + } +} + +export default Planner;
JavaScript
์ €๋Š” ์™œ ์ด๋ ‡๊ฒŒ ์ƒ๊ฐํ•˜์ง€ ๋ชปํ–ˆ๋˜ ๊ฑธ๊นŒ์š”...ใ…Žใ…Žใ…Ž ์ƒ์ˆ˜ํ™” ํ•ด๋†“๊ณ  ์ด์ƒํ•œ ์ง“์„ ํ–ˆ๋„ค์š”.
@@ -0,0 +1,105 @@ +package controller; + +import model.user.ChristmasUser; +import model.calendar.December; +import model.event.ChristmasEvent; +import view.InputView; +import view.OutputView; + +import java.util.Map; + +public class ChristmasController { + private static ChristmasUser user; + + public ChristmasController() { + user = new ChristmasUser(); + } + + public void startEvent() { + December.init(); + requestGreeting(); + requestReadDate(); + requestReadMenu(); + requestPrintGuide(); + printEvent(); + } + + public void printEvent(){ + requestSection(); + requestPrintMenu(); + requestSection(); + requestPrintAmountBefore(); + requestSection(); + requestPrintGiftMenu(); + requestSection(); + requestPrintBenefitsDetails(); + requestSection(); + requestPrintTotalBenefit(); + requestSection(); + requestPrintEstimatedAmountAfter(); + requestSection(); + requestPrintBadge(); + } + + public static void requestSection() { + OutputView.printSection(); + } + + public static void requestGreeting() { + OutputView.printGreeting(); + } + + public void requestReadDate() { + user.setDate(InputView.readDate()); + } + + public void requestReadMenu() { + user.setOrder(InputView.readMenu()); + } + + public static void requestPrintGuide() { + OutputView.printBenefitsGuide(user.getMonth(), user.getDay()); + } + + public void requestPrintMenu() { + OutputView.printMenu(user.getOrder()); + } + + public void requestPrintAmountBefore() { + user.sumAmountBefore(); + OutputView.printTotalOrderAmountBefore(user.getTotalPrice()); + } + + public void requestPrintGiftMenu() { + if (ChristmasEvent.getGiveChampagnePrice() <= user.getTotalPrice()) { + OutputView.printGiftMenu("์ƒดํŽ˜์ธ 1๊ฐœ"); + return; + } + OutputView.printGiftMenu("์—†์Œ"); + } + + public void requestPrintBenefitsDetails() { + Map<String, Integer> benefit = ChristmasEvent.ResultChristmasDDayDiscount(user.getDay(), + user.getTotalPrice(), + user.getOrder()); + OutputView.printBenefitsDetails(benefit, user.getTotalPrice()); + if (user.getTotalPrice()>=10000) + user.setTotalDiscount(benefit.values().stream().mapToInt(Integer::intValue).sum()); + } + + public void requestPrintTotalBenefit() { + OutputView.printTotalBenefit(user.getTotalDiscount()); + } + public void requestPrintEstimatedAmountAfter() { + if (ChristmasEvent.getGiveChampagnePrice() <= user.getTotalPrice()) { + OutputView.printEstimatedAmountAfter(user.getTotalPrice() - user.getTotalDiscount() + 25000); + return; + } + OutputView.printEstimatedAmountAfter(user.getTotalPrice() - user.getTotalDiscount()); + } + + public void requestPrintBadge() { + OutputView.printEventBadge(user.getTotalDiscount()); + } + +}
Java
10_000์„ ์ƒ์ˆ˜๋กœ ํฌ์žฅํ•˜๋ฉด ๋”์šฑ ์ข‹์€ ์ฝ”๋“œ๊ฐ€ ๋  ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,105 @@ +package controller; + +import model.user.ChristmasUser; +import model.calendar.December; +import model.event.ChristmasEvent; +import view.InputView; +import view.OutputView; + +import java.util.Map; + +public class ChristmasController { + private static ChristmasUser user; + + public ChristmasController() { + user = new ChristmasUser(); + } + + public void startEvent() { + December.init(); + requestGreeting(); + requestReadDate(); + requestReadMenu(); + requestPrintGuide(); + printEvent(); + } + + public void printEvent(){ + requestSection(); + requestPrintMenu(); + requestSection(); + requestPrintAmountBefore(); + requestSection(); + requestPrintGiftMenu(); + requestSection(); + requestPrintBenefitsDetails(); + requestSection(); + requestPrintTotalBenefit(); + requestSection(); + requestPrintEstimatedAmountAfter(); + requestSection(); + requestPrintBadge(); + } + + public static void requestSection() { + OutputView.printSection(); + } + + public static void requestGreeting() { + OutputView.printGreeting(); + } + + public void requestReadDate() { + user.setDate(InputView.readDate()); + } + + public void requestReadMenu() { + user.setOrder(InputView.readMenu()); + } + + public static void requestPrintGuide() { + OutputView.printBenefitsGuide(user.getMonth(), user.getDay()); + } + + public void requestPrintMenu() { + OutputView.printMenu(user.getOrder()); + } + + public void requestPrintAmountBefore() { + user.sumAmountBefore(); + OutputView.printTotalOrderAmountBefore(user.getTotalPrice()); + } + + public void requestPrintGiftMenu() { + if (ChristmasEvent.getGiveChampagnePrice() <= user.getTotalPrice()) { + OutputView.printGiftMenu("์ƒดํŽ˜์ธ 1๊ฐœ"); + return; + } + OutputView.printGiftMenu("์—†์Œ"); + } + + public void requestPrintBenefitsDetails() { + Map<String, Integer> benefit = ChristmasEvent.ResultChristmasDDayDiscount(user.getDay(), + user.getTotalPrice(), + user.getOrder()); + OutputView.printBenefitsDetails(benefit, user.getTotalPrice()); + if (user.getTotalPrice()>=10000) + user.setTotalDiscount(benefit.values().stream().mapToInt(Integer::intValue).sum()); + } + + public void requestPrintTotalBenefit() { + OutputView.printTotalBenefit(user.getTotalDiscount()); + } + public void requestPrintEstimatedAmountAfter() { + if (ChristmasEvent.getGiveChampagnePrice() <= user.getTotalPrice()) { + OutputView.printEstimatedAmountAfter(user.getTotalPrice() - user.getTotalDiscount() + 25000); + return; + } + OutputView.printEstimatedAmountAfter(user.getTotalPrice() - user.getTotalDiscount()); + } + + public void requestPrintBadge() { + OutputView.printEventBadge(user.getTotalDiscount()); + } + +}
Java
๋˜ `getter()`๋กœ ๊ฐ€์ ธ์™€์„œ ๊ฐ’์„ ๋น„๊ตํ•˜๊ธฐ ๋ณด๋‹จ `User`์— `isTotalPriceOver(int amount)`๋ผ๋Š” ๋ฉ”์„œ๋“œ๋ฅผ ์ถ”๊ฐ€๋กœ ๊ตฌํ˜„ํ•ด ์ค˜์„œ ๊ฐ’์— ๋Œ€ํ•œ ํŒ๋‹จ์€ User ํด๋ž˜์Šค ๋‚ด๋ถ€์—์„œ ํ•˜๋Š”๊ฒŒ ๋” ๊ฐ์ฒด์ง€ํ–ฅ์ ์ธ ์ฝ”๋“œ๊ฐ€ ๋  ๊ฒƒ ๊ฐ™์•„์šฉ
@@ -0,0 +1,16 @@ +package exception; + +public class InputValid { + private InputValid() { + + } + + public static int stringToInteger(String input, String errorType) { + for (int i = 0; i < input.length(); i++) { + if (!Character.isDigit(input.charAt(i))) { + throw new IllegalArgumentException("[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ " + errorType + "์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + } + return Integer.parseInt(input); + } +}
Java
`Integer.parseInt()` ๊ฐ€ ํŒŒ์‹ฑ ํ•  ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ์—” `NumberFormatException` ์„ ๋˜์ง€๊ธฐ ๋•Œ๋ฌธ์— ~~~java try( return Integer.parseInt(input) ) catch (NumberFormatException e) { throw new IllegalArgumentException(); } ~~~ ์ฒ˜๋Ÿผ ๋”์šฑ ๊ฐ„๊ฒฐํ•˜๊ฒŒ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ์–ด์š”!!
@@ -0,0 +1,16 @@ +package exception; + +public class InputValid { + private InputValid() { + + } + + public static int stringToInteger(String input, String errorType) { + for (int i = 0; i < input.length(); i++) { + if (!Character.isDigit(input.charAt(i))) { + throw new IllegalArgumentException("[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ " + errorType + "์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + } + return Integer.parseInt(input); + } +}
Java
ํ˜น์‹œ ๊ฒ€์ฆ ๋กœ์ง์„ ๋ถ„๋ฆฌํ•˜๊ณ  ์‹ถ์€ ์ด์œ ๋กœ ์ €๋ ‡๊ฒŒ ์ž‘์„ฑ ํ•œ๊ฑฐ๋ฉด ~~~java for (int i = 0; i < input.length(); i++) { if (!Character.isDigit(input.charAt(i))) { throw new IllegalArgumentException("[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ " + errorType + "์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); } } ~~~ ๋ฅผ `validateCanParseInt()` ๊ฐ™์€ ๋ฉ”์†Œ๋“œ๋กœ ๋ถ„๋ฆฌํ•ด ์ฃผ๋Š”๊ฒŒ ๋” ๋ณด๊ธฐ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,65 @@ +package exception; + +import model.menu.*; + +import java.util.Map; + +public class OrderMenu { + private OrderMenu() { + + } + + public static String[] menuFormat(String input) { + String[] itemInfo = input.split("-"); + + if (itemInfo.length != 2) { + throw new IllegalArgumentException("[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + + return itemInfo; + } + + public static int menuQuantityValid(String input) { + int num = InputValid.stringToInteger(input, "์ฃผ๋ฌธ"); + if (num < 1) { + throw new IllegalArgumentException("[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + + return num; + } + + public static void menuValid(String menuName) { + if (!ChristmasMenu.isValidAppetizer(menuName) && + !ChristmasMenu.isValidDessert(menuName) && + !ChristmasMenu.isValidDrink(menuName) && + !ChristmasMenu.isValidMain(menuName)) { + throw new IllegalArgumentException("[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + } + + public static void menuDuplication(Map<String, Integer> order, String menuName) { + if (order.containsKey(menuName)) { + throw new IllegalArgumentException("[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + } + + public static void maxNumMenu(Map<String, Integer> order) { + if (order.values().stream().mapToInt(Integer::intValue).sum() > 20) { + throw new IllegalArgumentException("[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + } + + public static void checkDrinkCount(Map<String, Integer> order) { + int drinkCount = 0; + + for (Drink menu : Drink.values()) { + if (order.containsKey(menu.getName())) { + drinkCount++; + } + } + + if (drinkCount == order.size()) { + throw new IllegalArgumentException("[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + } +}
Java
validateDuplicate() ๊ฐ™์€ ์ด๋ฆ„์ด ๋” ์–ด์šธ๋ฆด ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,65 @@ +package exception; + +import model.menu.*; + +import java.util.Map; + +public class OrderMenu { + private OrderMenu() { + + } + + public static String[] menuFormat(String input) { + String[] itemInfo = input.split("-"); + + if (itemInfo.length != 2) { + throw new IllegalArgumentException("[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + + return itemInfo; + } + + public static int menuQuantityValid(String input) { + int num = InputValid.stringToInteger(input, "์ฃผ๋ฌธ"); + if (num < 1) { + throw new IllegalArgumentException("[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + + return num; + } + + public static void menuValid(String menuName) { + if (!ChristmasMenu.isValidAppetizer(menuName) && + !ChristmasMenu.isValidDessert(menuName) && + !ChristmasMenu.isValidDrink(menuName) && + !ChristmasMenu.isValidMain(menuName)) { + throw new IllegalArgumentException("[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + } + + public static void menuDuplication(Map<String, Integer> order, String menuName) { + if (order.containsKey(menuName)) { + throw new IllegalArgumentException("[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + } + + public static void maxNumMenu(Map<String, Integer> order) { + if (order.values().stream().mapToInt(Integer::intValue).sum() > 20) { + throw new IllegalArgumentException("[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + } + + public static void checkDrinkCount(Map<String, Integer> order) { + int drinkCount = 0; + + for (Drink menu : Drink.values()) { + if (order.containsKey(menu.getName())) { + drinkCount++; + } + } + + if (drinkCount == order.size()) { + throw new IllegalArgumentException("[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + } +}
Java
~~~java boolean containsDrink = order.keySet().stream() .anyMatch(menu -> ChristmasMenu.isValidDrink(menu)) ~~~ ์ฒ˜๋Ÿผ Stream์„ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ์œผ๋ฉด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,19 @@ +package exception; + +public class VisitDate { + + private static Integer DateStart = 1; + private static Integer DateEnd = 31; + + private VisitDate() { + + } + /*๋‚ ์งœ ๋ฒ”์œ„๋ฅผ ํ™•์ธ ์ปค๋ฐ‹๋ฉ”์‹œ์ง€ ์‹ค์ˆ˜*/ + public static int checkDate(String input) { + int date = InputValid.stringToInteger(input, "๋‚ ์งœ"); + if (DateStart > date || DateEnd < date) { + throw new IllegalArgumentException("[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + return date; + } +}
Java
์ด ๋ฐฉ๋ฒ• ๋ณด๋‹ค๋Š” ๋‚ ์งœ ์ •๋ณด๋ฅผ ๋‹ด๊ณ  ์žˆ๋Š” Date๋ผ๋Š” ํด๋ž˜์Šค๋ฅผ ์ƒˆ๋กœ ๋งŒ๋“ค์–ด์„œ ๊ฐ์ฑ„ ์ƒ์„ฑ๊ณผ ๋™์‹œ์— ๊ฒ€์ฆ์„ ํ•˜๋Š”๊ฑด ์–ด๋–จ๊นŒ์š” ?? ~~~java class Date { final int value; public Date(int value) { validateDate(); this.value = value; } ~~~ ๊ฐ™์ด ํ™œ์šฉํ•˜๋ฉด ๋”์šฑ ๊ฐ์ฒด์ง€ํ–ฅ์ ์ธ ์ฝ”๋“œ๊ฐ€ ๋  ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,84 @@ +package model.calendar; + +import model.event.ChristmasEvent; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class December { + static private Map<Integer, Map<String, Object>> date = new HashMap<>(); + static private ArrayList<Integer> weekend = new ArrayList<Integer>() {{ + add(1); + add(2); + add(8); + add(9); + add(15); + add(16); + add(22); + add(23); + add(29); + add(30); + }}; + + static private ArrayList<Integer> starDay = new ArrayList<Integer>() {{ + add(3); + add(10); + add(17); + add(24); + add(25); + add(31); + }}; + + public static Map<String, Object> getDate(int day) { + return date.get(day); + } + + private December() { + } + + public static void init() { + initializeChristmasDiscountDates(); + initializeDefaultDiscountDates(); + } + + private static void initializeChristmasDiscountDates() { + int price = ChristmasEvent.getChristmasDDayDiscountInitPrice(); + int stepPrice = ChristmasEvent.getChristmasDDayDiscountStepPrice(); + + for (int i = 1; i < 32; i++) { + Map<String, Object> tmpData = createDiscountDate(price, i); + date.put(i, tmpData); + price += stepPrice; + } + } + + private static void initializeDefaultDiscountDates() { + for (int i = 26; i < 32; i++) { + Map<String, Object> tmpData = createDiscountDate(0, i); + date.put(i, tmpData); + } + } + + private static Map<String, Object> createDiscountDate(int price, int day) { + Map<String, Object> tmpData = new HashMap<>(); + tmpData.put("ํ• ์ธ๊ธˆ์•ก", price); + tmpData.put("์˜์—…์ผ", getDayType(day)); + tmpData.put("๋ณ„์œ ๋ฌด", isStar(day)); + return tmpData; + } + + public static String getDayType(Integer day) { + if (weekend.contains(day)) { + return "์ฃผ๋ง"; + } + return "ํ‰์ผ"; + } + + public static boolean isStar(Integer day) { + if (starDay.contains(day)) { + return true; + } + return false; + } +}
Java
`List.of()`๋‚˜ `Arrays.asList()` ๋ฅผ ํ™œ์šฉํ•˜๋ฉด ~~~java List.of(1,2,8,9...); Arrays.asList(1,2,8,9...); ~~~ ์ฒ˜๋Ÿผ ๊ฐ„๊ฒฐํ•˜๊ฒŒ ์“ธ ์ˆ˜ ์žˆ์–ด์š”!
@@ -0,0 +1,84 @@ +package model.calendar; + +import model.event.ChristmasEvent; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class December { + static private Map<Integer, Map<String, Object>> date = new HashMap<>(); + static private ArrayList<Integer> weekend = new ArrayList<Integer>() {{ + add(1); + add(2); + add(8); + add(9); + add(15); + add(16); + add(22); + add(23); + add(29); + add(30); + }}; + + static private ArrayList<Integer> starDay = new ArrayList<Integer>() {{ + add(3); + add(10); + add(17); + add(24); + add(25); + add(31); + }}; + + public static Map<String, Object> getDate(int day) { + return date.get(day); + } + + private December() { + } + + public static void init() { + initializeChristmasDiscountDates(); + initializeDefaultDiscountDates(); + } + + private static void initializeChristmasDiscountDates() { + int price = ChristmasEvent.getChristmasDDayDiscountInitPrice(); + int stepPrice = ChristmasEvent.getChristmasDDayDiscountStepPrice(); + + for (int i = 1; i < 32; i++) { + Map<String, Object> tmpData = createDiscountDate(price, i); + date.put(i, tmpData); + price += stepPrice; + } + } + + private static void initializeDefaultDiscountDates() { + for (int i = 26; i < 32; i++) { + Map<String, Object> tmpData = createDiscountDate(0, i); + date.put(i, tmpData); + } + } + + private static Map<String, Object> createDiscountDate(int price, int day) { + Map<String, Object> tmpData = new HashMap<>(); + tmpData.put("ํ• ์ธ๊ธˆ์•ก", price); + tmpData.put("์˜์—…์ผ", getDayType(day)); + tmpData.put("๋ณ„์œ ๋ฌด", isStar(day)); + return tmpData; + } + + public static String getDayType(Integer day) { + if (weekend.contains(day)) { + return "์ฃผ๋ง"; + } + return "ํ‰์ผ"; + } + + public static boolean isStar(Integer day) { + if (starDay.contains(day)) { + return true; + } + return false; + } +}
Java
Enum์„ ์ ๊ทน ํ™œ์šฉํ•ด ๋ณด์‹œ๋Š”๊ฑธ ์ถ”์ฒœ๋“œ๋ ค์š”!
@@ -0,0 +1,84 @@ +package model.calendar; + +import model.event.ChristmasEvent; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class December { + static private Map<Integer, Map<String, Object>> date = new HashMap<>(); + static private ArrayList<Integer> weekend = new ArrayList<Integer>() {{ + add(1); + add(2); + add(8); + add(9); + add(15); + add(16); + add(22); + add(23); + add(29); + add(30); + }}; + + static private ArrayList<Integer> starDay = new ArrayList<Integer>() {{ + add(3); + add(10); + add(17); + add(24); + add(25); + add(31); + }}; + + public static Map<String, Object> getDate(int day) { + return date.get(day); + } + + private December() { + } + + public static void init() { + initializeChristmasDiscountDates(); + initializeDefaultDiscountDates(); + } + + private static void initializeChristmasDiscountDates() { + int price = ChristmasEvent.getChristmasDDayDiscountInitPrice(); + int stepPrice = ChristmasEvent.getChristmasDDayDiscountStepPrice(); + + for (int i = 1; i < 32; i++) { + Map<String, Object> tmpData = createDiscountDate(price, i); + date.put(i, tmpData); + price += stepPrice; + } + } + + private static void initializeDefaultDiscountDates() { + for (int i = 26; i < 32; i++) { + Map<String, Object> tmpData = createDiscountDate(0, i); + date.put(i, tmpData); + } + } + + private static Map<String, Object> createDiscountDate(int price, int day) { + Map<String, Object> tmpData = new HashMap<>(); + tmpData.put("ํ• ์ธ๊ธˆ์•ก", price); + tmpData.put("์˜์—…์ผ", getDayType(day)); + tmpData.put("๋ณ„์œ ๋ฌด", isStar(day)); + return tmpData; + } + + public static String getDayType(Integer day) { + if (weekend.contains(day)) { + return "์ฃผ๋ง"; + } + return "ํ‰์ผ"; + } + + public static boolean isStar(Integer day) { + if (starDay.contains(day)) { + return true; + } + return false; + } +}
Java
์—ฌ๊ธฐ๋„ ๋ฌธ์ž์—ด์„ ๊ทธ๋Œ€๋กœ ๋ฐ˜ํ™˜ํ•˜๊ธฐ๋ณด๋‹จ `WEEKDAY` `WEEKEND`๋ฅผ ๊ฐ€์ง„ `Enum`์„ ๋งŒ๋“ค์–ด์„œ ๊ทธ ๊ฐ์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒŒ ๋” ์ข‹์•„๋ณด์—ฌ์š”!
@@ -0,0 +1,31 @@ +package model.event; + +public enum Badge { + STAR(5000), + TREE(10000), + SANTA(20000); + + private int price = 0; + + Badge(int price) { + this.price = price; + } + + public int getPrice() { + return price; + } + + public static String getBadgeType(int price) { + if (SANTA.getPrice() <= price) { + return "์‚ฐํƒ€"; + } + if (TREE.getPrice() <= price) { + return "ํŠธ๋ฆฌ"; + } + if (STAR.getPrice() <= price) { + return "๋ณ„"; + } + + return "์—†์Œ"; + } +}
Java
์ด๋Ÿฌ๋ฉด Enum์„ ์‚ฌ์šฉํ•œ ์ด์œ ๊ฐ€ ์—†์–ด๋ณด์—ฌ์š” ,, String ๋Œ€์‹  Enum์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒŒ ๋” ์ข‹์•„๋ณด์ž…๋‹ˆ๋‹ค !
@@ -0,0 +1,24 @@ +package model.menu; + +public enum Main { + T_BONE_STEAK("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 55000), + BBQ_RIBS("๋ฐ”๋น„ํ๋ฆฝ", 54000), + SEAFOOD_PASTA("ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", 35000), + CHRISTMAS_PASTA("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", 25000); + + private String name = ""; + private int price = 0; + + Main(String name, int price) { + this.name = name; + this.price = price; + } + + public int getPrice() { + return price; + } + + public String getName() { + return name; + } +}
Java
Menu๋ผ๋Š” Enum ํ•˜๋‚˜๋ฅผ ๋งŒ๋“ค๊ณ  ๊ทธ ์•ˆ์— Category๋ฅผ ๋””์ €ํŠธ, ์• ํ”ผํƒ€์ด์ € ๋“ฑ๋“ฑ์œผ๋กœ ๋‚˜๋ˆ ๋‘๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,16 @@ +package core.mvc.tobe; + +import javax.servlet.http.HttpServletRequest; + +public class DefaultMethodArgumentResolver implements HandlerMethodArgumentResolver { + + @Override + public Object resolveArgument(MethodParameter methodParameter, HttpServletRequest request) { + return request.getParameter(methodParameter.getParameterName()); + } + + @Override + public boolean supportsParameter(MethodParameter methodParameter) { + return true; + } +}
Java
ํ•ด๋‹น ํด๋ž˜์Šค์—์„œ wrapperํด๋ž˜์Šค๋„ ์ง€์›ํ•ด์ฃผ๋ฉด ์ข‹๊ฒ ๋„ค์š”. ClassUtils.isPrimitiveOrWrapper ๋“ฑ์„ ์ฐธ๊ณ ํ•ด๋ณด์„ธ์š”~
@@ -0,0 +1,16 @@ +package core.mvc.tobe; + +import javax.servlet.http.HttpServletRequest; + +public class DefaultMethodArgumentResolver implements HandlerMethodArgumentResolver { + + @Override + public Object resolveArgument(MethodParameter methodParameter, HttpServletRequest request) { + return request.getParameter(methodParameter.getParameterName()); + } + + @Override + public boolean supportsParameter(MethodParameter methodParameter) { + return true; + } +}
Java
true๋ณด๋‹ค๋„ PrimitiveOrWrapper์ธ์ง€ ํ™•์ธํ•  ์ˆ˜ ์žˆ์œผ๋ฉด ์ข‹๊ฒ ๋„ค์š”.
@@ -0,0 +1,16 @@ +package core.mvc.tobe; + +import javax.servlet.http.HttpServletRequest; + +public class DefaultMethodArgumentResolver implements HandlerMethodArgumentResolver { + + @Override + public Object resolveArgument(MethodParameter methodParameter, HttpServletRequest request) { + return request.getParameter(methodParameter.getParameterName()); + } + + @Override + public boolean supportsParameter(MethodParameter methodParameter) { + return true; + } +}
Java
Primitive argument์ง€์›๊ณผ HttpServletRequest argument ์ง€์›์€ ๋‚˜๋ˆ„์–ด์ง€๋Š”๊ฒŒ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,24 @@ +package core.mvc.tobe; + +import javax.servlet.http.HttpServletRequest; + +import next.model.User; + +public class UserMethodArgumentResolver implements HandlerMethodArgumentResolver { + + @Override + public Object resolveArgument(MethodParameter methodParameter, HttpServletRequest request) { + String userId = request.getParameter("userId"); + String password = request.getParameter("password"); + String name = request.getParameter("name"); + String email = request.getParameter("email"); + + return new User(userId, password, name, email); + } + + @Override + public boolean supportsParameter(MethodParameter methodParameter) { + Class<?> parameterType = methodParameter.getParameterType(); + return parameterType.equals(User.class); + } +}
Java
์ด์™€ ๊ฐ™์ด ๊ตฌํ˜„ํ•  ๊ฒฝ์šฐ User ๊ฐ์ฒด๋งŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๊ณ  ๋ฒ”์šฉ์ ์œผ๋กœ ์‚ฌ์šฉํ•˜๋Š”๋ฐ๋Š” ํ•œ๊ณ„๊ฐ€ ์žˆ์ง€ ์•Š์„๊นŒ? java bean ๊ทœ์•ฝ์„ ๋”ฐ๋ฅด๋Š” ๋ชจ๋“  ๊ฐ์ฒด์— ๋Œ€ํ•ด ์ž๋™ ๋งคํ•‘ํ•  ์ˆ˜ ์žˆ๋„๋ก ๊ตฌํ˜„ํ•ด ๋ณด๋ฉด ์–ด๋–จ๊นŒ? request๋กœ ์ „๋‹ฌ๋˜๋Š” ๋ฐ์ดํ„ฐ์— ํ•ด๋‹นํ•˜๋Š” setter ๋ฉ”์„œ๋“œ๊ฐ€ ์žˆ์œผ๋ฉด ์ž๋™์œผ๋กœ ๊ฐ’์„ ํ• ๋‹นํ•œ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด request.getParameter("userId") ๊ฐ’์ด ์กด์žฌํ•˜๋ฉด setUserId()๋ฅผ ํ†ตํ•ด ๊ฐ’์„ ํ• ๋‹นํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ๊ตฌํ˜„ํ•ด์•ผ java bean ๊ทœ์•ฝ์„ ๋”ฐ๋ฅด๋Š” ๊ฐ์ฒด์— ๋ฒ”์šฉ์ ์œผ๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์ง€ ์•Š์„๊นŒ?
@@ -0,0 +1,24 @@ +package core.mvc.tobe; + +import javax.servlet.http.HttpServletRequest; + +import next.model.User; + +public class UserMethodArgumentResolver implements HandlerMethodArgumentResolver { + + @Override + public Object resolveArgument(MethodParameter methodParameter, HttpServletRequest request) { + String userId = request.getParameter("userId"); + String password = request.getParameter("password"); + String name = request.getParameter("name"); + String email = request.getParameter("email"); + + return new User(userId, password, name, email); + } + + @Override + public boolean supportsParameter(MethodParameter methodParameter) { + Class<?> parameterType = methodParameter.getParameterType(); + return parameterType.equals(User.class); + } +}
Java
ํฌ๋น„๋‹˜! ๋ง์”€ํ•˜์‹  java bean ๊ทœ์•ฝ์— ๋Œ€ํ•ด์„œ๋Š” PrimitiveMethodArgumentResolver, WrapperMethodArgumentResolver ์—์„œ ๊ตฌํ˜„ํ•˜๊ณ  ์žˆ๋Š”๋ฐ์š”. ํ˜น์‹œ ์ด๊ฒƒ๋งŒ์œผ๋กœ๋Š” ๋ถ€์กฑํ•œ ๊ฒƒ์ผ๊นŒ์š”?
@@ -10,11 +10,14 @@ "preview": "vite preview" }, "dependencies": { + "add": "^2.0.6", "react": "^18.2.0", "react-dom": "^18.2.0", + "react-hook-form": "^7.45.4", "react-router-dom": "^6.14.2", "recoil": "^0.7.7", "styled-components": "^6.0.7", + "yarn": "^1.22.19", "zustand": "^4.4.1" }, "devDependencies": {
Unknown
yarn ํŒจํ‚ค์ง€ ์„ค์น˜๋Š” ์‹ค์ˆ˜์ธ๊ฐ€์šฉ~?
@@ -0,0 +1,19 @@ +import * as S from "./styled"; + +const Button = (props: { + text: string; + type: "button" | "submit" | "reset"; + bgColor: "black" | "grey" | "hidden"; + onClick?: React.MouseEventHandler<HTMLButtonElement>; +}) => { + const { type, text, bgColor, onClick } = props; + return ( + <> + <S.DefaultButton type={type} onClick={onClick} colortype={bgColor}> + {text} + </S.DefaultButton> + </> + ); +}; + +export default Button;
Unknown
jsx๋ฅผ ์™œ ๋นˆํƒœ๊ทธ๋กœ ๋ž˜ํ•‘ํ•˜์…จ๋‚˜์—ฌ?
@@ -0,0 +1,19 @@ +import * as S from "./styled"; + +const Button = (props: { + text: string; + type: "button" | "submit" | "reset"; + bgColor: "black" | "grey" | "hidden"; + onClick?: React.MouseEventHandler<HTMLButtonElement>; +}) => { + const { type, text, bgColor, onClick } = props; + return ( + <> + <S.DefaultButton type={type} onClick={onClick} colortype={bgColor}> + {text} + </S.DefaultButton> + </> + ); +}; + +export default Button;
Unknown
Button Props์„ ์ง€์ •ํ•ด์ฃผ์‹คEo Native element attributes๋ฅผ ๋„ฃ์ง€์•Š์€ ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์—ฌ?
@@ -0,0 +1,76 @@ +import { styled } from "styled-components"; + +// input +export const RegisterInput = styled.input` + padding: 1rem; + border-radius: 8px; +`; + +// label text +export const InputLabelText = styled.div` + padding: 1rem 0; + font-weight: 600; + font-size: 16px; + color: #222; +`; + +// button +export const DefaultButton = styled.button<{ + colortype: "black" | "grey" | "hidden"; +}>` + width: 100%; + background-color: ${(props) => + props.colortype === "black" + ? "#222" + : props.colortype === "grey" + ? "#ddd" + : "#f0f0f0"}; + color: ${(props) => + props.colortype === "black" + ? "#fff" + : props.colortype === "grey" + ? "#222" + : "#cdcdcd"}; + font-weight: 700; + padding: 1rem; + border: 0; + cursor: ${(props) => (props.colortype === "hidden" ? "default" : "pointer")}; + border-radius: 8px; +`; + +// titleText +export const TitleBoldText = styled.div` + width: 100%; + padding-top: 1rem; + text-align: center; + font-size: 2rem; + font-weight: 600; + color: #222; +`; + +// text contents +export const TextContentsGreatingContainer = styled.div` + height: calc(100vh - 200px); + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + font-size: 24px; + color: #222; + text-align: center; +`; + +export const TextContentsGreatingName = styled.div` + font-size: 24px; + font-weight: 600; + color: blueviolet; +`; + +export const TextContentsGreatingDescription = styled.div` + font-size: 24px; +`; + +export const GreetingNameContainer = styled.div` + display: flex; + flex-direction: row; +`;
TypeScript
Button Props ํƒ€์ž…์„ ์ง€์ •ํ•ด์ฃผ์ง€ ์•Š์€ ์ด์œ ๊ฐ€ ๋ฌด์—‡์ผ๊นŒ์š”?
@@ -0,0 +1,76 @@ +import { styled } from "styled-components"; + +// input +export const RegisterInput = styled.input` + padding: 1rem; + border-radius: 8px; +`; + +// label text +export const InputLabelText = styled.div` + padding: 1rem 0; + font-weight: 600; + font-size: 16px; + color: #222; +`; + +// button +export const DefaultButton = styled.button<{ + colortype: "black" | "grey" | "hidden"; +}>` + width: 100%; + background-color: ${(props) => + props.colortype === "black" + ? "#222" + : props.colortype === "grey" + ? "#ddd" + : "#f0f0f0"}; + color: ${(props) => + props.colortype === "black" + ? "#fff" + : props.colortype === "grey" + ? "#222" + : "#cdcdcd"}; + font-weight: 700; + padding: 1rem; + border: 0; + cursor: ${(props) => (props.colortype === "hidden" ? "default" : "pointer")}; + border-radius: 8px; +`; + +// titleText +export const TitleBoldText = styled.div` + width: 100%; + padding-top: 1rem; + text-align: center; + font-size: 2rem; + font-weight: 600; + color: #222; +`; + +// text contents +export const TextContentsGreatingContainer = styled.div` + height: calc(100vh - 200px); + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + font-size: 24px; + color: #222; + text-align: center; +`; + +export const TextContentsGreatingName = styled.div` + font-size: 24px; + font-weight: 600; + color: blueviolet; +`; + +export const TextContentsGreatingDescription = styled.div` + font-size: 24px; +`; + +export const GreetingNameContainer = styled.div` + display: flex; + flex-direction: row; +`;
TypeScript
์ด๋ ‡๊ฒŒ hex ์ฝ”๋“œ๊ฐ€ ๊ทธ๋Œ€๋กœ ๋…ธ์ถœ๋˜๋Š”๊ฒƒ์€ ๋งค์ง๋„˜๋ฒ„๊ฐ€ ์•„๋‹๊นŒ ์‹ถ์Šด๋‹ค ์ƒ์ˆ˜์ฒ˜๋ฆฌํ•ด์ฃผ๋ฉด ์–ด๋–จ๊นŒ์š”?
@@ -4,19 +4,20 @@ import { Routes, Route } from "react-router-dom"; // Components import Home from "./Home"; +import SignUp from "./SignUp"; const Router = () => { - const [isInLogged, setisInLogged] = useState(true); + const [isInLogged, setIsInLogged] = useState(false); return ( <> {isInLogged ? ( <Routes> - <Route path="/" element={<Home />} /> + <Route path="/" element={<Home setIsInLogged={setIsInLogged} />} /> </Routes> ) : ( <Routes> - <Route /> + <Route path="/" element={<SignUp setIsInLogged={setIsInLogged} />} /> </Routes> )} </>
Unknown
์ปดํฌ๋„ŒํŠธ๋Š” Login ์ธ๋ฐ InLogged๋Š” ๋„ค์ด๋ฐ ๋ถˆ์ผ์น˜ ์•„๋‹๊นŒ์š”?
@@ -0,0 +1,60 @@ +import { + UseFormRegister, + FieldValues, + UseFormWatch, + UseFormGetValues, + UseFormSetValue, +} from "react-hook-form"; +import Button from "../atoms/Button"; +import Input from "../atoms/Input"; +import * as S from "./styled"; + +type InputAndButtonPropsType = { + type: "button" | "submit" | "reset"; + name: string; + onClick: () => void; + register: UseFormRegister<FieldValues>; + watch: UseFormWatch<FieldValues>; + getValues?: UseFormGetValues<FieldValues>; + setValue?: UseFormSetValue<FieldValues>; + isEmailPass?: boolean; +}; + +// ๋ฒ„ํŠผ๊ณผ ํ•จ๊ป˜ ์“ฐ๋Š” ์ธํ’‹ ์ปดํฌ๋„ŒํŠธ +const InputAndButton = (props: InputAndButtonPropsType) => { + const { + onClick: checkValiable, + type, + name, + register, + getValues, + setValue, + watch, + isEmailPass, + } = props; + return ( + <> + <S.InputAndButtonContainer> + <Input + name={name} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + {isEmailPass ? ( + <Button text={"์ค‘๋ณต ํ™•์ธ ์™„๋ฃŒ"} type={"button"} bgColor={"hidden"} /> + ) : ( + <Button + type={type} + text={"์ค‘๋ณต ํ™•์ธํ•˜๊ธฐ"} + bgColor={"grey"} + onClick={checkValiable} + /> + )} + </S.InputAndButtonContainer> + </> + ); +}; + +export default InputAndButton;
Unknown
์ธํ’‹๊ณผ ๋ฒ„ํŠผ์„ ํ•จ๊ป˜ ์‚ฌ์šฉํ•˜๋Š” ์ด์œ ๊ฐ€ ์–ด๋–ค ์ด์œ ์—์„œ ์žˆ์—ˆ์„๊นŒ์š”? ๋ถ€๋ชจ ์ปดํฌ๋„ŒํŠธ์—์„œ input๊ณผ button์„ ์ ์ ˆํžˆ ์‚ฌ์šฉํ•ด์ฃผ๋ฉด ๋˜๋Š”๋ฐ ์ด๋ ‡๊ฒŒ ๋ถ„๋ฆฌํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•จ๋‹ค
@@ -0,0 +1,190 @@ +/** + * + * ์ด๋ฆ„ + * ์ด๋ฉ”์ผ (์ค‘๋ณต ํ™•์ธ ๋ฒ„ํŠผ) + * ๋น„๋ฐ€๋ฒˆํ˜ธ + * ๋น„๋ฐ€๋ฒˆํ˜ธ ์žฌํ™•์ธ + * ํšŒ์›๊ฐ€์ž… ๋ฒ„ํŠผ + * + */ + +import Button from "../atoms/Button"; +import Input from "../atoms/Input"; +import LabelText from "../atoms/LabelText"; +import TitleTex from "../atoms/TitleText"; +import InputAndButton from "../molecules/InputAndButton"; +import { useForm } from "react-hook-form"; +import * as S from "./styled"; +import { CONSTANTS } from "../../constants"; +import { useState } from "react"; + +type SignUpFormPropsType = { + setIsInLogged: React.Dispatch<React.SetStateAction<boolean>>; +}; +const SignUpForm = (props: SignUpFormPropsType) => { + const { setIsInLogged } = props; + const [isEmailPass, setIsEmailPass] = useState(false); + const { + REGEXP: { EMAIL_CHECK, PASSWORD_CHECK }, + } = CONSTANTS; + + const { getValues, watch, register, setValue } = useForm(); + + const emailRegex = EMAIL_CHECK; + const pwdRegex = PASSWORD_CHECK; + + const setLocalData = () => { + const userData = { + name: getValues("userName"), + phone: getValues("userPhoneNumber"), + password: getValues("userPwd"), + email: getValues("userEmail"), + }; + + const jsonUserData = JSON.stringify(userData); + + return localStorage.setItem("loginData", jsonUserData); + }; + + const submitData = () => { + // ๋“ฑ๋ก ํ›„ + if (!isEmailPass) { + return alert("์ด๋ฉ”์ผ์„ ํ™•์ธํ•ด์ฃผ์„ธ์š”."); + } + + alert("ํšŒ์›๊ฐ€์ž…์„ ์ถ•ํ•˜ํ•ฉ๋‹ˆ๋‹ค."); + setLocalData(); + return setIsInLogged(true); + }; + + const checkPwdVariable = () => { + const userPwd = getValues("userPwd") as string; + if (userPwd.length < 2 || userPwd.length > 20) { + return alert( + "๋น„๋ฐ€๋ฒˆํ˜ธ๋Š” ํŠน์ˆ˜๋ฌธ์ž 1๊ฐœ ํฌํ•จํ•˜์—ฌ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”(์ตœ์†Œ 2์ž~์ตœ๋Œ€20์ž)" + ); + } + + if (!pwdRegex.test(userPwd)) { + return alert( + "๋น„๋ฐ€๋ฒˆํ˜ธ๋Š” ํŠน์ˆ˜๋ฌธ์ž 1๊ฐœ ํฌํ•จํ•˜์—ฌ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”(์ตœ์†Œ 2์ž~์ตœ๋Œ€20์ž)" + ); + } + + if (!(getValues("checkUserPwd") === userPwd)) { + return alert("๋น„๋ฐ€๋ฒˆํ˜ธ ํ™•์ธ์ด ์ผ์น˜ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } + + return true; + }; + + const checkEmailVariable = () => { + // ์ด๋ฉ”์ผ check + if (!getValues("userEmail")) { + return alert("์ด๋ฉ”์ผ์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } + + if (!emailRegex.test(getValues("userEmail"))) { + return alert("์˜ฌ๋ฐ”๋ฅธ ์ด๋ฉ”์ผ์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } + + const localUserEmail = JSON.parse( + localStorage.getItem("loginData") || "" + ).email; + + if (localUserEmail === getValues("userEmail")) { + return alert("์ค‘๋ณต๋œ ์ด๋ฉ”์ผ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } + setIsEmailPass(true); + return true; + }; + + const checkUserData = ( + e: React.MouseEvent<HTMLButtonElement, MouseEvent> + ) => { + e.preventDefault(); + + if (getValues("userName").length < 3) { + return alert("์ด๋ฆ„์„ 3์ž์ด์ƒ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } + + if (!getValues("userPhoneNumber")) { + return alert("ํœด๋Œ€ํฐ ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } + + if (!checkEmailVariable()) { + return false; + } + + if (!checkPwdVariable()) { + return false; + } + + return submitData(); + }; + + return ( + <S.Container> + <S.Form> + <TitleTex>{"ํšŒ์›๊ฐ€์ž…"}</TitleTex> + <LabelText>{"์ด๋ฆ„"}</LabelText> + <Input + type={"text"} + name={"userName"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <LabelText>{"ํœด๋Œ€ํฐ ๋ฒˆํ˜ธ"}</LabelText> + <Input + type={"number"} + name={"userPhoneNumber"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <LabelText>{"์ด๋ฉ”์ผ"}</LabelText> + <InputAndButton + type={"button"} + name={"userEmail"} + onClick={checkEmailVariable} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + isEmailPass={isEmailPass} + /> + <LabelText>{"๋น„๋ฐ€๋ฒˆํ˜ธ"}</LabelText> + <Input + type={"password"} + name={"userPwd"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <LabelText>{"๋น„๋ฐ€๋ฒˆํ˜ธ ํ™•์ธ"}</LabelText> + <Input + type={"password"} + name={"checkUserPwd"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <S.SignUpButtonContainer> + <Button + type={"submit"} + text={"ํšŒ์›๊ฐ€์ž…"} + bgColor={"black"} + onClick={(e) => checkUserData(e)} + /> + </S.SignUpButtonContainer> + </S.Form> + </S.Container> + ); +}; + +export default SignUpForm;
Unknown
์—ฌ๊ธฐ์„œ๋Š” input button์„ ๋‘˜๋‹ค ์“ฐ๋ฉด์„œ InputAndButton์„ ์“ฐ๊ธฐ๋„ํ•ด์„œ ์ปดํฌ๋„ŒํŠธ ์„ค๊ณ„์— ๋Œ€ํ•œ ์ผ๊ด€์„ฑ์ด ์•ˆ๋ณด์ธ๋‹ค? ์ œ๊ฐ€ ์•„ํ† ๋ฏน ๋””์ž์ธํŒจํ„ด์„ ์™„๋ฒฝํ•˜๊ฒŒ ์ดํ•ดํ•˜์ง€๋Š” ๋ชปํ•˜๊ณ ์žˆ๋‹ค๋Š”์  ์•Œ์•„์ฃผ์„ธ์š” ํผ ์ปดํฌ๋„ŒํŠธ๋ผ๊ณ  ํ•˜๋Š”๋ฐ ํผ์ปดํฌ๋„ŒํŠธ์—์„œ ์–ด๋–ค ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜์ง€ ์†”์งํ•˜๊ฒŒ ์ž˜ ๋ณด์ด์งˆ์•Š์Šต๋‹ˆ๋‹ค! ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ณด๊ณ ์žˆ์œผ๋ฉด ์ด ์ปดํฌ๋„ŒํŠธ์—์„œ๋Š” ์–ด๋–ค ์ผ์„ ํ• ์ง€๊ฐ€ ๋ณด์—ฌ์•ผํ•˜๋Š”๋ฐ ์ž˜ ๋ณด์ด์ง€๊ฐ€ ์•Š๋Š”๋‹ค?
@@ -0,0 +1,36 @@ +import { + FieldValues, + UseFormGetValues, + UseFormRegister, + UseFormSetValue, + UseFormWatch, + useForm, +} from "react-hook-form"; +import * as S from "./styled"; +import { useEffect } from "react"; + +type InputPropsType = { + type?: string; + placeholder?: string; + name: string; + register: UseFormRegister<FieldValues>; + watch: UseFormWatch<FieldValues>; + getValues?: UseFormGetValues<FieldValues>; + setValue?: UseFormSetValue<FieldValues>; +}; + +const Input = (props: InputPropsType) => { + const { type, placeholder, name, register } = props; + + return ( + <> + <S.RegisterInput + type={type} + placeholder={placeholder} + {...register(name)} + ></S.RegisterInput> + </> + ); +}; + +export default Input;
Unknown
Native input ์–ดํŠธ๋ฆฌ๋ทฐํŠธ๋ฅผ ๊ณ ๋ คํ•ด๋ด๋„ ์ข‹์„๊ฒƒ๊ฐ™์Šต๋‹ˆ๋‹ค ๊ทธ๋ฆฌ๊ณ  watch์™€ ๊ฐ™์€ ๋ฉ”์„œ๋“œ๋ฅผ ํ•ด๋‹น ์ปดํฌ๋„ŒํŠธ์—์„œ ์•Œ์•„์•ผํ• ๊นŒ์š”? ์‚ฌ์šฉ์ฒ˜์—์„œ ์•Œ๊ณ ์žˆ์–ด์•ผํ•˜๋Š” ๋ฉ”์„œ๋“œ์ผํ…๋ฐ ๊ณผ๋„ํ•œ ์ •๋ณด๊ฐ€ ์•„๋‹๊นŒ์‹ถ๋„ค์š”!
@@ -0,0 +1,8 @@ +import * as S from "./styled"; + +const LabelText = (props: { children: string }) => { + const { children } = props; + return <S.InputLabelText>{children}</S.InputLabelText>; +}; + +export default LabelText;
Unknown
Props Type ์ปจ๋ฒค์…˜ ์ง€์ผœ์ฃผ์„ธ์š”
@@ -0,0 +1,21 @@ +import * as S from "./styled"; + +const TextContents = () => { + const userName = JSON.parse(localStorage.getItem("loginData") || "").name; + + return ( + <S.TextContentsGreatingContainer> + <S.GreetingNameContainer> + <S.TextContentsGreatingName>{userName}</S.TextContentsGreatingName> + <S.TextContentsGreatingDescription> + {"๋‹˜,"} + </S.TextContentsGreatingDescription> + </S.GreetingNameContainer> + <S.TextContentsGreatingDescription> + {"ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค."} + </S.TextContentsGreatingDescription> + </S.TextContentsGreatingContainer> + ); +}; + +export default TextContents;
Unknown
์ด ๊ฒฝ์šฐ์—” TextContents๊ฐ€ ์ˆœ์ˆ˜ํ•œ ํ˜•ํƒœ๋ผ๊ณ  ํ• ์ˆ˜์žˆ์„๊นŒ์—ฌ? ์‚ฌ์šฉ์ฒ˜์—์„œ userName์„ ํ”„๋ž์Šค๋กœ ์ „๋‹ฌํ•ด์คฌ๋‹ค๋ฉด ์ˆœ์ˆ˜ํ–ˆ์„๊ฒƒ๊ฐ™์€๋ฐ์š”!
@@ -0,0 +1,27 @@ +import Button from "../atoms/Button"; +import TextContents from "../atoms/TextContents"; +import TitleTex from "../atoms/TitleText"; +import * as S from "./styled"; + +type MainPropsType = { + setIsInLogged: React.Dispatch<React.SetStateAction<boolean>>; +}; + +const Main = (props: MainPropsType) => { + return ( + <S.Container> + <TitleTex>{"ํ™ˆ"}</TitleTex> + <TextContents /> + <S.SignUpButtonContainer> + <Button + text={"๋กœ๊ทธ์•„์›ƒ"} + bgColor={"black"} + type={"button"} + onClick={() => props.setIsInLogged(false)} + /> + </S.SignUpButtonContainer> + </S.Container> + ); +}; + +export default Main;
Unknown
setState๋ฅผ ํ”„๋ž์Šค๋กœ ์ „๋‹ฌํ•˜์ง€์•Š๊ณ  setState๋ฅผ ๋ž˜ํ•‘ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์ „๋‹ฌํ–ˆ์œผ๋ฉด ์•„๋ž˜์™€ ๊ฐ™์ด ํŽธํ•˜๊ฒŒ ์ „๋‹ฌ์ด ๊ฐ€๋Šฅํ•˜์ง€์•Š์•˜์„๊นŒ์—ฌ? ```ts setIsInLogged: (state : boolean) => void ```
@@ -0,0 +1,190 @@ +/** + * + * ์ด๋ฆ„ + * ์ด๋ฉ”์ผ (์ค‘๋ณต ํ™•์ธ ๋ฒ„ํŠผ) + * ๋น„๋ฐ€๋ฒˆํ˜ธ + * ๋น„๋ฐ€๋ฒˆํ˜ธ ์žฌํ™•์ธ + * ํšŒ์›๊ฐ€์ž… ๋ฒ„ํŠผ + * + */ + +import Button from "../atoms/Button"; +import Input from "../atoms/Input"; +import LabelText from "../atoms/LabelText"; +import TitleTex from "../atoms/TitleText"; +import InputAndButton from "../molecules/InputAndButton"; +import { useForm } from "react-hook-form"; +import * as S from "./styled"; +import { CONSTANTS } from "../../constants"; +import { useState } from "react"; + +type SignUpFormPropsType = { + setIsInLogged: React.Dispatch<React.SetStateAction<boolean>>; +}; +const SignUpForm = (props: SignUpFormPropsType) => { + const { setIsInLogged } = props; + const [isEmailPass, setIsEmailPass] = useState(false); + const { + REGEXP: { EMAIL_CHECK, PASSWORD_CHECK }, + } = CONSTANTS; + + const { getValues, watch, register, setValue } = useForm(); + + const emailRegex = EMAIL_CHECK; + const pwdRegex = PASSWORD_CHECK; + + const setLocalData = () => { + const userData = { + name: getValues("userName"), + phone: getValues("userPhoneNumber"), + password: getValues("userPwd"), + email: getValues("userEmail"), + }; + + const jsonUserData = JSON.stringify(userData); + + return localStorage.setItem("loginData", jsonUserData); + }; + + const submitData = () => { + // ๋“ฑ๋ก ํ›„ + if (!isEmailPass) { + return alert("์ด๋ฉ”์ผ์„ ํ™•์ธํ•ด์ฃผ์„ธ์š”."); + } + + alert("ํšŒ์›๊ฐ€์ž…์„ ์ถ•ํ•˜ํ•ฉ๋‹ˆ๋‹ค."); + setLocalData(); + return setIsInLogged(true); + }; + + const checkPwdVariable = () => { + const userPwd = getValues("userPwd") as string; + if (userPwd.length < 2 || userPwd.length > 20) { + return alert( + "๋น„๋ฐ€๋ฒˆํ˜ธ๋Š” ํŠน์ˆ˜๋ฌธ์ž 1๊ฐœ ํฌํ•จํ•˜์—ฌ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”(์ตœ์†Œ 2์ž~์ตœ๋Œ€20์ž)" + ); + } + + if (!pwdRegex.test(userPwd)) { + return alert( + "๋น„๋ฐ€๋ฒˆํ˜ธ๋Š” ํŠน์ˆ˜๋ฌธ์ž 1๊ฐœ ํฌํ•จํ•˜์—ฌ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”(์ตœ์†Œ 2์ž~์ตœ๋Œ€20์ž)" + ); + } + + if (!(getValues("checkUserPwd") === userPwd)) { + return alert("๋น„๋ฐ€๋ฒˆํ˜ธ ํ™•์ธ์ด ์ผ์น˜ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } + + return true; + }; + + const checkEmailVariable = () => { + // ์ด๋ฉ”์ผ check + if (!getValues("userEmail")) { + return alert("์ด๋ฉ”์ผ์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } + + if (!emailRegex.test(getValues("userEmail"))) { + return alert("์˜ฌ๋ฐ”๋ฅธ ์ด๋ฉ”์ผ์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } + + const localUserEmail = JSON.parse( + localStorage.getItem("loginData") || "" + ).email; + + if (localUserEmail === getValues("userEmail")) { + return alert("์ค‘๋ณต๋œ ์ด๋ฉ”์ผ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } + setIsEmailPass(true); + return true; + }; + + const checkUserData = ( + e: React.MouseEvent<HTMLButtonElement, MouseEvent> + ) => { + e.preventDefault(); + + if (getValues("userName").length < 3) { + return alert("์ด๋ฆ„์„ 3์ž์ด์ƒ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } + + if (!getValues("userPhoneNumber")) { + return alert("ํœด๋Œ€ํฐ ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } + + if (!checkEmailVariable()) { + return false; + } + + if (!checkPwdVariable()) { + return false; + } + + return submitData(); + }; + + return ( + <S.Container> + <S.Form> + <TitleTex>{"ํšŒ์›๊ฐ€์ž…"}</TitleTex> + <LabelText>{"์ด๋ฆ„"}</LabelText> + <Input + type={"text"} + name={"userName"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <LabelText>{"ํœด๋Œ€ํฐ ๋ฒˆํ˜ธ"}</LabelText> + <Input + type={"number"} + name={"userPhoneNumber"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <LabelText>{"์ด๋ฉ”์ผ"}</LabelText> + <InputAndButton + type={"button"} + name={"userEmail"} + onClick={checkEmailVariable} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + isEmailPass={isEmailPass} + /> + <LabelText>{"๋น„๋ฐ€๋ฒˆํ˜ธ"}</LabelText> + <Input + type={"password"} + name={"userPwd"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <LabelText>{"๋น„๋ฐ€๋ฒˆํ˜ธ ํ™•์ธ"}</LabelText> + <Input + type={"password"} + name={"checkUserPwd"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <S.SignUpButtonContainer> + <Button + type={"submit"} + text={"ํšŒ์›๊ฐ€์ž…"} + bgColor={"black"} + onClick={(e) => checkUserData(e)} + /> + </S.SignUpButtonContainer> + </S.Form> + </S.Container> + ); +}; + +export default SignUpForm;
Unknown
Submit ํ•จ์ˆ˜๋‚ด๋ถ€์—์„œ ์œ ํšจ์„ฑ๊ฒ€์‚ฌ์˜ ๊ฒฐ๊ณผ๋กœ ์œ ์ €์—๊ฒŒ ๋…ธ์ถœ์‹œํ‚ค๋Š”๊ฒƒ์ด ์•„๋‹ˆ๋ผ Submit ์ด๋ฒคํŠธ๋ฅผ ๋ง‰์•„๋ฒ„๋ ธ์œผ๋ฉด ์–ด๋–จ๊นŒ์—ฌ? ์˜ˆ๋ฅผ๋“ค์–ด ์œ ํšจ์„ฑ๊ฒ€์‚ฌ๋ฅผ ์‹คํŒจํ–ˆ๋‹ค๋ฉด ๋ฒ„ํŠผ์˜ disabled์ฒ˜๋ฆฌ๋„ ๊ณ ๋ คํ•ด๋ณผ์ˆ˜์žˆ์„๊ฒƒ๊ฐ™์Šต๋‹ˆ๋‹ค ๊ทผ๋ฐ ์ด๊ฑด ๊ธฐํš๊ณผ ๋งž๋ฌผ๋ฆฌ๋Š”๊ฑฐ๋‹ˆ๊นŒ!
@@ -0,0 +1,190 @@ +/** + * + * ์ด๋ฆ„ + * ์ด๋ฉ”์ผ (์ค‘๋ณต ํ™•์ธ ๋ฒ„ํŠผ) + * ๋น„๋ฐ€๋ฒˆํ˜ธ + * ๋น„๋ฐ€๋ฒˆํ˜ธ ์žฌํ™•์ธ + * ํšŒ์›๊ฐ€์ž… ๋ฒ„ํŠผ + * + */ + +import Button from "../atoms/Button"; +import Input from "../atoms/Input"; +import LabelText from "../atoms/LabelText"; +import TitleTex from "../atoms/TitleText"; +import InputAndButton from "../molecules/InputAndButton"; +import { useForm } from "react-hook-form"; +import * as S from "./styled"; +import { CONSTANTS } from "../../constants"; +import { useState } from "react"; + +type SignUpFormPropsType = { + setIsInLogged: React.Dispatch<React.SetStateAction<boolean>>; +}; +const SignUpForm = (props: SignUpFormPropsType) => { + const { setIsInLogged } = props; + const [isEmailPass, setIsEmailPass] = useState(false); + const { + REGEXP: { EMAIL_CHECK, PASSWORD_CHECK }, + } = CONSTANTS; + + const { getValues, watch, register, setValue } = useForm(); + + const emailRegex = EMAIL_CHECK; + const pwdRegex = PASSWORD_CHECK; + + const setLocalData = () => { + const userData = { + name: getValues("userName"), + phone: getValues("userPhoneNumber"), + password: getValues("userPwd"), + email: getValues("userEmail"), + }; + + const jsonUserData = JSON.stringify(userData); + + return localStorage.setItem("loginData", jsonUserData); + }; + + const submitData = () => { + // ๋“ฑ๋ก ํ›„ + if (!isEmailPass) { + return alert("์ด๋ฉ”์ผ์„ ํ™•์ธํ•ด์ฃผ์„ธ์š”."); + } + + alert("ํšŒ์›๊ฐ€์ž…์„ ์ถ•ํ•˜ํ•ฉ๋‹ˆ๋‹ค."); + setLocalData(); + return setIsInLogged(true); + }; + + const checkPwdVariable = () => { + const userPwd = getValues("userPwd") as string; + if (userPwd.length < 2 || userPwd.length > 20) { + return alert( + "๋น„๋ฐ€๋ฒˆํ˜ธ๋Š” ํŠน์ˆ˜๋ฌธ์ž 1๊ฐœ ํฌํ•จํ•˜์—ฌ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”(์ตœ์†Œ 2์ž~์ตœ๋Œ€20์ž)" + ); + } + + if (!pwdRegex.test(userPwd)) { + return alert( + "๋น„๋ฐ€๋ฒˆํ˜ธ๋Š” ํŠน์ˆ˜๋ฌธ์ž 1๊ฐœ ํฌํ•จํ•˜์—ฌ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”(์ตœ์†Œ 2์ž~์ตœ๋Œ€20์ž)" + ); + } + + if (!(getValues("checkUserPwd") === userPwd)) { + return alert("๋น„๋ฐ€๋ฒˆํ˜ธ ํ™•์ธ์ด ์ผ์น˜ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } + + return true; + }; + + const checkEmailVariable = () => { + // ์ด๋ฉ”์ผ check + if (!getValues("userEmail")) { + return alert("์ด๋ฉ”์ผ์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } + + if (!emailRegex.test(getValues("userEmail"))) { + return alert("์˜ฌ๋ฐ”๋ฅธ ์ด๋ฉ”์ผ์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } + + const localUserEmail = JSON.parse( + localStorage.getItem("loginData") || "" + ).email; + + if (localUserEmail === getValues("userEmail")) { + return alert("์ค‘๋ณต๋œ ์ด๋ฉ”์ผ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } + setIsEmailPass(true); + return true; + }; + + const checkUserData = ( + e: React.MouseEvent<HTMLButtonElement, MouseEvent> + ) => { + e.preventDefault(); + + if (getValues("userName").length < 3) { + return alert("์ด๋ฆ„์„ 3์ž์ด์ƒ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } + + if (!getValues("userPhoneNumber")) { + return alert("ํœด๋Œ€ํฐ ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } + + if (!checkEmailVariable()) { + return false; + } + + if (!checkPwdVariable()) { + return false; + } + + return submitData(); + }; + + return ( + <S.Container> + <S.Form> + <TitleTex>{"ํšŒ์›๊ฐ€์ž…"}</TitleTex> + <LabelText>{"์ด๋ฆ„"}</LabelText> + <Input + type={"text"} + name={"userName"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <LabelText>{"ํœด๋Œ€ํฐ ๋ฒˆํ˜ธ"}</LabelText> + <Input + type={"number"} + name={"userPhoneNumber"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <LabelText>{"์ด๋ฉ”์ผ"}</LabelText> + <InputAndButton + type={"button"} + name={"userEmail"} + onClick={checkEmailVariable} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + isEmailPass={isEmailPass} + /> + <LabelText>{"๋น„๋ฐ€๋ฒˆํ˜ธ"}</LabelText> + <Input + type={"password"} + name={"userPwd"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <LabelText>{"๋น„๋ฐ€๋ฒˆํ˜ธ ํ™•์ธ"}</LabelText> + <Input + type={"password"} + name={"checkUserPwd"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <S.SignUpButtonContainer> + <Button + type={"submit"} + text={"ํšŒ์›๊ฐ€์ž…"} + bgColor={"black"} + onClick={(e) => checkUserData(e)} + /> + </S.SignUpButtonContainer> + </S.Form> + </S.Container> + ); +}; + +export default SignUpForm;
Unknown
setLocalData ํ•จ์ˆ˜๋„ค์ž„์„ ๋ณด๊ณ  ์ด๊ฒŒ ๋ญ”์—ญํ• ์„ํ•˜๋Š”๊ฑฐ์ง€ ์‹ถ๋„ค์š” setLocalStorageData๋ผ๊ณ  ์ž‘๋ช…ํ•˜๋Š”๊ฑด ์–ด๋• ์„๊นŒ์—ฌ
@@ -0,0 +1,190 @@ +/** + * + * ์ด๋ฆ„ + * ์ด๋ฉ”์ผ (์ค‘๋ณต ํ™•์ธ ๋ฒ„ํŠผ) + * ๋น„๋ฐ€๋ฒˆํ˜ธ + * ๋น„๋ฐ€๋ฒˆํ˜ธ ์žฌํ™•์ธ + * ํšŒ์›๊ฐ€์ž… ๋ฒ„ํŠผ + * + */ + +import Button from "../atoms/Button"; +import Input from "../atoms/Input"; +import LabelText from "../atoms/LabelText"; +import TitleTex from "../atoms/TitleText"; +import InputAndButton from "../molecules/InputAndButton"; +import { useForm } from "react-hook-form"; +import * as S from "./styled"; +import { CONSTANTS } from "../../constants"; +import { useState } from "react"; + +type SignUpFormPropsType = { + setIsInLogged: React.Dispatch<React.SetStateAction<boolean>>; +}; +const SignUpForm = (props: SignUpFormPropsType) => { + const { setIsInLogged } = props; + const [isEmailPass, setIsEmailPass] = useState(false); + const { + REGEXP: { EMAIL_CHECK, PASSWORD_CHECK }, + } = CONSTANTS; + + const { getValues, watch, register, setValue } = useForm(); + + const emailRegex = EMAIL_CHECK; + const pwdRegex = PASSWORD_CHECK; + + const setLocalData = () => { + const userData = { + name: getValues("userName"), + phone: getValues("userPhoneNumber"), + password: getValues("userPwd"), + email: getValues("userEmail"), + }; + + const jsonUserData = JSON.stringify(userData); + + return localStorage.setItem("loginData", jsonUserData); + }; + + const submitData = () => { + // ๋“ฑ๋ก ํ›„ + if (!isEmailPass) { + return alert("์ด๋ฉ”์ผ์„ ํ™•์ธํ•ด์ฃผ์„ธ์š”."); + } + + alert("ํšŒ์›๊ฐ€์ž…์„ ์ถ•ํ•˜ํ•ฉ๋‹ˆ๋‹ค."); + setLocalData(); + return setIsInLogged(true); + }; + + const checkPwdVariable = () => { + const userPwd = getValues("userPwd") as string; + if (userPwd.length < 2 || userPwd.length > 20) { + return alert( + "๋น„๋ฐ€๋ฒˆํ˜ธ๋Š” ํŠน์ˆ˜๋ฌธ์ž 1๊ฐœ ํฌํ•จํ•˜์—ฌ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”(์ตœ์†Œ 2์ž~์ตœ๋Œ€20์ž)" + ); + } + + if (!pwdRegex.test(userPwd)) { + return alert( + "๋น„๋ฐ€๋ฒˆํ˜ธ๋Š” ํŠน์ˆ˜๋ฌธ์ž 1๊ฐœ ํฌํ•จํ•˜์—ฌ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”(์ตœ์†Œ 2์ž~์ตœ๋Œ€20์ž)" + ); + } + + if (!(getValues("checkUserPwd") === userPwd)) { + return alert("๋น„๋ฐ€๋ฒˆํ˜ธ ํ™•์ธ์ด ์ผ์น˜ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } + + return true; + }; + + const checkEmailVariable = () => { + // ์ด๋ฉ”์ผ check + if (!getValues("userEmail")) { + return alert("์ด๋ฉ”์ผ์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } + + if (!emailRegex.test(getValues("userEmail"))) { + return alert("์˜ฌ๋ฐ”๋ฅธ ์ด๋ฉ”์ผ์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } + + const localUserEmail = JSON.parse( + localStorage.getItem("loginData") || "" + ).email; + + if (localUserEmail === getValues("userEmail")) { + return alert("์ค‘๋ณต๋œ ์ด๋ฉ”์ผ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } + setIsEmailPass(true); + return true; + }; + + const checkUserData = ( + e: React.MouseEvent<HTMLButtonElement, MouseEvent> + ) => { + e.preventDefault(); + + if (getValues("userName").length < 3) { + return alert("์ด๋ฆ„์„ 3์ž์ด์ƒ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } + + if (!getValues("userPhoneNumber")) { + return alert("ํœด๋Œ€ํฐ ๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } + + if (!checkEmailVariable()) { + return false; + } + + if (!checkPwdVariable()) { + return false; + } + + return submitData(); + }; + + return ( + <S.Container> + <S.Form> + <TitleTex>{"ํšŒ์›๊ฐ€์ž…"}</TitleTex> + <LabelText>{"์ด๋ฆ„"}</LabelText> + <Input + type={"text"} + name={"userName"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <LabelText>{"ํœด๋Œ€ํฐ ๋ฒˆํ˜ธ"}</LabelText> + <Input + type={"number"} + name={"userPhoneNumber"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <LabelText>{"์ด๋ฉ”์ผ"}</LabelText> + <InputAndButton + type={"button"} + name={"userEmail"} + onClick={checkEmailVariable} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + isEmailPass={isEmailPass} + /> + <LabelText>{"๋น„๋ฐ€๋ฒˆํ˜ธ"}</LabelText> + <Input + type={"password"} + name={"userPwd"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <LabelText>{"๋น„๋ฐ€๋ฒˆํ˜ธ ํ™•์ธ"}</LabelText> + <Input + type={"password"} + name={"checkUserPwd"} + register={register} + getValues={getValues} + setValue={setValue} + watch={watch} + /> + <S.SignUpButtonContainer> + <Button + type={"submit"} + text={"ํšŒ์›๊ฐ€์ž…"} + bgColor={"black"} + onClick={(e) => checkUserData(e)} + /> + </S.SignUpButtonContainer> + </S.Form> + </S.Container> + ); +}; + +export default SignUpForm;
Unknown
์ด๋Ÿฐ ์œ ํšจ์„ฑ๊ฒ€์‚ฌ๋กœ์ง์€ ์™ธ๋ถ€์— ๋ชจ๋“ˆํ™”ํ•˜์—ฌ ์‚ฌ์šฉํ•˜๋Š”๊ฑด ์–ด๋–˜์„๊นŒ์š”? ๊ทธ๋ฆฌ๊ณ  ๋ฆฌ์•กํŠธ ํ›…ํผ ์‚ฌ์šฉํ•˜์‹ ๋‹ค๋ฉด https://www.react-hook-form.com/advanced-usage/#CustomHookwithResolver ์ด๋Ÿฐ๊ฒƒ๋„ ์žˆ์Šด๋‹ค
@@ -4,19 +4,20 @@ import { Routes, Route } from "react-router-dom"; // Components import Home from "./Home"; +import SignUp from "./SignUp"; const Router = () => { - const [isInLogged, setisInLogged] = useState(true); + const [isInLogged, setIsInLogged] = useState(false); return ( <> {isInLogged ? ( <Routes> - <Route path="/" element={<Home />} /> + <Route path="/" element={<Home setIsInLogged={setIsInLogged} />} /> </Routes> ) : ( <Routes> - <Route /> + <Route path="/" element={<SignUp setIsInLogged={setIsInLogged} />} /> </Routes> )} </>
Unknown
์ด๋ ‡๊ฒŒ ๋กœ๊ทธ์ธ ์ƒํƒœ์—ฌ๋ถ€๋ฅผ Router์—์„œ ํ•˜๋Š”๊ฒƒ์ด ์•„๋‹ˆ๋ผ ์ „์—ญ์œผ๋กœ ๊ด€๋ฆฌํ•˜๋Š”๊ฒŒ ์–ด๋• ์„๊นŒ์—ฌ? ๋ผ์šฐํ„ฐ ์ปดํฌ๋„ŒํŠธ๋Š” url์— ๋งคํ•‘๋˜๋Š” ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ Œ๋”ํ•ด์ฃผ๋Š” ์—ญํ• ์ด๋ผ๊ณ  ์ƒ๊ฐ๋˜์–ด์„œ์—ฌ! ํ•ด๋‹น ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋กœ๊ทธ์ธ ์ƒํƒœ์—ฌ๋ถ€๊นŒ์ง€ ์•Œ์•„์•ผํ–ˆ์„๊นŒ์š”?
@@ -0,0 +1,11 @@ +import SignUpForm from "../components/organisms/SignUpForm"; + +type SignUpFormPropsType = { + setIsInLogged: React.Dispatch<React.SetStateAction<boolean>>; +}; + +const SignUp = (props: SignUpFormPropsType) => { + return <SignUpForm setIsInLogged={props.setIsInLogged} />; +}; + +export default SignUp;
Unknown
์ด๋ถ€๋ถ„๋„ ์ž˜ ์ดํ•ด๊ฐ€ ๋˜์ง€์•Š๋Š”๋ฐ Form ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋กœ๊ทธ์ธ์—ฌ๋ถ€๋ฅผ ์•Œ์•„์•ผํ•˜๋Š” ์ด์œ ๊ฐ€ ์—†๋‹ค๊ณ  ์ƒ๊ฐ๋ฉ๋‹ˆ๋‹ค..! ์ปดํฌ๋„ŒํŠธ์—๊ฒŒ ์ „๋‹ฌ๋˜๋Š” prop์€ ์ปดํฌ๋„ŒํŠธ๊ฐ€ ์•Œ์•„์•ผํ•˜๋Š” ์ •๋ณด์˜ ๋ฒ”์œ„๋ฅผ ๋‚˜ํƒ€๋‚ธ๋‹ค๊ณ  ๋ด์š”
@@ -0,0 +1,59 @@ +import accumulator.Accumulator; +import accumulator.PostFixAccumulator; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +public class CalculatorTest { + + + @ParameterizedTest + @DisplayName("๋ง์…ˆ") + @CsvSource(value = {"1 2 + 3 + : 6", "10 20 + 30 + : 60", + "100 200 + 300 + : 600"}, delimiter = ':') + public void postFixAddCalculate(String expression, int expectResult) { + Accumulator postFixAccumulator = new PostFixAccumulator(); + int result = postFixAccumulator.calculate(expression); + Assertions.assertEquals(expectResult, result); + } + + @ParameterizedTest + @DisplayName("๋บผ์…ˆ") + @CsvSource(value = {"1 2 - 3 -: -4", "10 30 - 20 -: -40", "300 200 - 1 - : 99"}, delimiter = ':') + public void postFixMinusCalculate(String expression, int expectResult) { + Accumulator postFixAccumulator = new PostFixAccumulator(); + int result = postFixAccumulator.calculate(expression); + Assertions.assertEquals(expectResult, result); + } + + @ParameterizedTest + @DisplayName("๊ณฑ์…ˆ") + @CsvSource(value = {"1 2 * 3 *: 6", "10 20 * 30 *: 6000", + "100 200 * 300 * : 6000000"}, delimiter = ':') + public void postFixMultiplyCalculate(String expression, int expectResult) { + Accumulator postFixAccumulator = new PostFixAccumulator(); + int result = postFixAccumulator.calculate(expression); + Assertions.assertEquals(expectResult, result); + } + + @ParameterizedTest + @DisplayName("๋‚˜๋ˆ—์…ˆ") + @CsvSource(value = {"100 10 / 1 / : 10", "10 2 / : 5", "10000 20 / 10 / : 50"}, delimiter = ':') + public void postFixDivideCalculate(String expression, int expectResult) { + Accumulator postFixAccumulator = new PostFixAccumulator(); + int result = postFixAccumulator.calculate(expression); + Assertions.assertEquals(expectResult, result); + } + + @ParameterizedTest + @DisplayName("์‚ฌ์น™์—ฐ์‚ฐ") + @CsvSource(value = {"5 3 2 * + 8 4 / - : 9", "7 4 * 2 / 3 + 1 - : 16", + "9 5 - 2 * 6 3 / +: 10"}, delimiter = ':') + public void PostFixCalculate(String expression, int expectResult) { + PostFixAccumulator calculator = new PostFixAccumulator(); + int result = calculator.calculate(expression); + Assertions.assertEquals(expectResult, result); + } + +}
Java
์—ฌ๊ธฐ๋„ ์ปจ๋ฒค์…˜์ด ์ซŒ... ๊ฐ ๋ฉ”์„œ๋“œ ์‚ฌ์ด๋Š” ๋„์›Œ ์ฃผ์‹œ๋Š”๊ฒŒ ์›์น™์ด๊ณ  IDE๋ฌธ์ œ์ธ๊ฑด์ง€ ์ œ๊ฐ€ ๋ณด๋Š” ํ™˜๋ฉด์ด ๋ฌธ์ œ์ธ๊ฑด์ง€ class ๋‹จ์œ„์™€ ๋ฉ”์„œ๋“œ ๋‹จ์œ„์— ๋Œ€ํ•œ ๋ธ”๋Ÿญ์ด ๊ตฌ๋ถ„๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ์ด ๋˜ํ•œ ์ง€์ผœ์ฃผ์…จ์œผ๋ฉด ์ข‹๊ฒ ์Šต๋‹ˆ๋‹ค. ๋˜ํ•œ ์ง€๊ธˆ ํ•˜๋‚˜์˜ ์˜ˆ์‹œ์— ๋Œ€ํ•œ ํ…Œ์ŠคํŠธ ์ฝ”๋“œ๋งŒ ์ž‘์„ฑํ•˜์‹  ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. @ParameterizedTest ๋ฅผ ๊ณต๋ถ€ํ•ด๋ณด์‹œ๋Š”๊ฒŒ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,117 @@ +# Created by https://www.toptal.com/developers/gitignore/api/intellij +# Edit at https://www.toptal.com/developers/gitignore?templates=intellij + +### Intellij ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +# Azure Toolkit for IntelliJ plugin +# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij +.idea/**/azureSettings.xml + +# End of https://www.toptal.com/developers/gitignore/api/intellij \ No newline at end of file
Unknown
์ด์ชฝ ๋ถ€๋ถ„ ์˜ต์…˜์œผ๋กœ ์–ด๋– ํ•œ ๋‚ด์—ญ ์ถ”๊ฐ€ํ–ˆ๋Š”์ง€ ์•Œ๋ ค์ฃผ์‹ค ์ˆ˜ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,9 @@ +package input; + +public interface Input { + + public String selectInput(); + + public String expressionInput(); + +}
Java
์ œ๋„ˆ๋ฆญ์„ ์‚ฌ์šฉํ•œ ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”? Input์€ ๋ฐ”์ดํŠธ ํ˜น์€ ๋ฌธ์ž์—ด๋กœ ๋“ค์–ด์˜ฌํ…๋ฐ ์–ด๋– ํ•œ ์ƒ๊ฐ์œผ๋กœ ์ œ๋„ˆ๋ฆญ์„ ์‚ฌ์šฉํ–ˆ๋Š”์ง€๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹น
@@ -0,0 +1,9 @@ + +import calculator.Calculator; + +public class main { + + public static void main(String[] args) { + new Calculator().run(); + } +}
Java
IOException์ด ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์ด ์‹คํ–‰๋˜๋Š” ๋ถ€๋ถ„๊นŒ์ง€ ์ „ํŒŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ์ด๋Ÿฌ๋ฉด ์ž…์ถœ๋ ฅ ์˜ˆ์™ธ ๋ฐœ์ƒ ์‹œ ํ”„๋กœ๊ทธ๋žจ์ด ๋น„์ •์ƒ์ ์œผ๋กœ ์ข…๋ฃŒ๋  ๊ฐ€๋Šฅ์„ฑ์ด ์žˆ๊ฒ ๋„ค์š”.
@@ -0,0 +1,20 @@ +package repository; + +import java.util.ArrayList; +import java.util.List; + +public class Repository { + + private List<String> list = new ArrayList<>(); + + public void store(String expression, String result) { + StringBuilder formattedExpression = new StringBuilder(expression).append(" = ").append(result); + list.add(formattedExpression.toString()); + + } + + public List<String> getResult() { + return new ArrayList<>(list); + } + +}
Java
์ €์žฅ์†Œ๋ฅผ List๋กœ ํ‘œํ˜„ํ•˜์‹  ์ด์œ ๋ฅผ ์•Œ ์ˆ˜ ์žˆ์„๊นŒ์š”? ๋™์ผํ•œ ์—ฐ์‚ฐ์‹์ด์—ฌ๋„ ๋ฆฌ์ŠคํŠธ์— ์ถ”๊ฐ€ํ•˜๋Š”๊ฒŒ ๋งž์„๊นŒ์š”? ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ์ตœ๋Œ€ํ•œ ์•„๋‚„ ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์„ ์ƒ๊ฐํ•ด๋ณด๋Š”๊ฒŒ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,19 @@ +import convertor.InfixToPostfixConverter; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +public class ChangToPostfixTest { + + @ParameterizedTest + @DisplayName("์ค‘์œ„ ํ‘œ๊ธฐ์‹ ํ›„์œ„ ํ‘œ๊ธฐ์‹ ๋ณ€ํ™˜") + @CsvSource(value = {"7 * 4 / 2 + 3 - 1 :'7 4 * 2 / 3 + 1 - '", + "9 - 5 * 2 + 6 / 3: '9 5 2 * - 6 3 / + '"}, delimiter = ':') + public void InfixToPostfixTest(String infixExpression, String postFinExpression) { + InfixToPostfixConverter calculator = new InfixToPostfixConverter(); + String result = calculator.changeToPostFix(infixExpression); + Assertions.assertEquals(postFinExpression, result); + } + +}
Java
ํ…Œ์ŠคํŠธ ์ฝ”๋“œ ๋‚ด์šฉ์ด ๋งŽ์ด ๋ถ€์‹คํ•ฉ๋‹ˆ๋‹ค. ๋‹จ์œ„ ํ…Œ์ŠคํŠธ์— ๋Œ€ํ•ด์„œ ์ƒ๊ฐํ•ด๋ณด์…จ์œผ๋ฉด ์ข‹๊ฒ ์Šต๋‹ˆ๋‹ค. ์ ์–ด๋„ ์ž‘์„ฑํ•˜์‹  ์ฝ”๋“œ์—์„œ View ์˜์—ญ์„ ์ œ์™ธํ•œ ๋‚˜๋จธ์ง€ ์˜์—ญ์€ ํ…Œ์ŠคํŠธ๊ฐ€ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.
@@ -2,13 +2,30 @@ package com.petqua.application.product.review import com.amazonaws.services.s3.AmazonS3 import com.ninjasquad.springmockk.SpykBean +import com.petqua.application.product.dto.MemberProductReviewReadQuery import com.petqua.application.product.dto.ProductReviewCreateCommand import com.petqua.common.domain.findByIdOrThrow +import com.petqua.domain.delivery.DeliveryMethod +import com.petqua.domain.member.MemberRepository +import com.petqua.domain.order.OrderNumber +import com.petqua.domain.order.OrderPayment +import com.petqua.domain.order.OrderPaymentRepository +import com.petqua.domain.order.OrderRepository +import com.petqua.domain.order.OrderStatus.PURCHASE_CONFIRMED +import com.petqua.domain.product.ProductRepository +import com.petqua.domain.product.option.Sex import com.petqua.domain.product.review.ProductReviewImageRepository import com.petqua.domain.product.review.ProductReviewRepository +import com.petqua.domain.store.StoreRepository import com.petqua.exception.product.review.ProductReviewException import com.petqua.exception.product.review.ProductReviewExceptionType import com.petqua.test.DataCleaner +import com.petqua.test.fixture.member +import com.petqua.test.fixture.order +import com.petqua.test.fixture.product +import com.petqua.test.fixture.productReview +import com.petqua.test.fixture.productReviewImage +import com.petqua.test.fixture.store import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.BehaviorSpec import io.kotest.matchers.shouldBe @@ -18,12 +35,18 @@ import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE import org.springframework.http.MediaType import org.springframework.mock.web.MockMultipartFile +import java.math.BigDecimal @SpringBootTest(webEnvironment = NONE) class ProductReviewFacadeServiceTest( private val productReviewFacadeService: ProductReviewFacadeService, private val productReviewRepository: ProductReviewRepository, private val productReviewImageRepository: ProductReviewImageRepository, + private val orderRepository: OrderRepository, + private val memberRepository: MemberRepository, + private val storeRepository: StoreRepository, + private val productRepository: ProductRepository, + private val orderPaymentRepository: OrderPaymentRepository, private val dataCleaner: DataCleaner, @SpykBean @@ -225,6 +248,151 @@ class ProductReviewFacadeServiceTest( } } + Given("์‚ฌ์šฉ์ž๊ฐ€ ๋ฆฌ๋ทฐ๋ฅผ ์ž‘์„ฑํ•œ ํ›„ ์ž์‹ ์˜ ๋ฆฌ๋ทฐ ๋‚ด์—ญ์„ ์กฐํšŒํ•  ๋•Œ") { + val member = memberRepository.save(member(nickname = "์ฟ ์•„")) + val store = storeRepository.save(store(name = "ํŽซ์ฟ ์•„")) + val productA = productRepository.save( + product( + name = "์ƒํ’ˆA", + storeId = store.id, + discountPrice = BigDecimal.ZERO, + reviewCount = 0, + reviewTotalScore = 0 + ) + ) + val productB = productRepository.save( + product( + name = "์ƒํ’ˆB", + storeId = store.id, + discountPrice = BigDecimal.ZERO, + reviewCount = 0, + reviewTotalScore = 0 + ) + ) + val orderA = orderRepository.save( + order( + orderNumber = OrderNumber.from("202402211607020ORDERNUMBER"), + memberId = member.id, + storeId = store.id, + storeName = store.name, + quantity = 1, + totalAmount = BigDecimal.ONE, + productId = productA.id, + productName = productA.name, + thumbnailUrl = productA.thumbnailUrl, + deliveryMethod = DeliveryMethod.SAFETY, + sex = Sex.FEMALE, + ) + ) + val orderB = orderRepository.save( + order( + orderNumber = OrderNumber.from("202402211607021ORDERNUMBER"), + memberId = member.id, + storeId = store.id, + storeName = store.name, + quantity = 1, + totalAmount = BigDecimal.ONE, + productId = productB.id, + productName = productB.name, + thumbnailUrl = productB.thumbnailUrl, + deliveryMethod = DeliveryMethod.SAFETY, + sex = Sex.FEMALE, + ) + ) + orderPaymentRepository.saveAll( + listOf( + OrderPayment( + orderId = orderA.id, + status = PURCHASE_CONFIRMED + ), + OrderPayment( + orderId = orderB.id, + status = PURCHASE_CONFIRMED + ) + ) + ) + + val productReviewA = productReviewRepository.save( + productReview( + productId = productA.id, + reviewerId = member.id, + score = 5, + recommendCount = 1, + hasPhotos = true, + content = "์ƒํ’ˆA ์ •๋ง ์ข‹์•„์š”!" + ) + ) + val productReviewB = productReviewRepository.save( + productReview( + productId = productB.id, + reviewerId = member.id, + score = 5, + recommendCount = 1, + hasPhotos = false, + content = "์ƒํ’ˆB ์ •๋ง ์ข‹์•„์š”!" + ) + ) + + productReviewImageRepository.saveAll( + listOf( + productReviewImage(imageUrl = "imageA1", productReviewId = productReviewA.id), + productReviewImage(imageUrl = "imageA2", productReviewId = productReviewA.id) + ) + ) + + When("ํšŒ์›์˜ Id๋ฅผ ์ž…๋ ฅํ•ด ์กฐํšŒํ•˜๋ฉด") { + val memberProductReviewsResponse = productReviewFacadeService.readMemberProductReviews( + MemberProductReviewReadQuery( + memberId = member.id + ) + ) + + Then("๋ฆฌ๋ทฐ ๋‚ด์—ญ์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค") { + val memberProductReviews = memberProductReviewsResponse.memberProductReviews + + memberProductReviews.size shouldBe 2 + + val memberProductReviewB = memberProductReviews[0] + memberProductReviewB.reviewId shouldBe productReviewB.id + memberProductReviewB.memberId shouldBe productReviewB.memberId + memberProductReviewB.createdAt shouldBe orderB.createdAt + memberProductReviewB.orderStatus shouldBe PURCHASE_CONFIRMED.name + memberProductReviewB.storeId shouldBe orderB.orderProduct.storeId + memberProductReviewB.storeId shouldBe orderB.orderProduct.storeId + memberProductReviewB.storeName shouldBe orderB.orderProduct.storeName + memberProductReviewB.productId shouldBe orderB.orderProduct.productId + memberProductReviewB.productName shouldBe orderB.orderProduct.productName + memberProductReviewB.productThumbnailUrl shouldBe orderB.orderProduct.thumbnailUrl + memberProductReviewB.quantity shouldBe orderB.orderProduct.quantity + memberProductReviewB.sex shouldBe orderB.orderProduct.sex.name + memberProductReviewB.deliveryMethod shouldBe orderB.orderProduct.deliveryMethod.name + memberProductReviewB.score shouldBe productReviewB.score.value + memberProductReviewB.content shouldBe productReviewB.content.value + memberProductReviewB.recommendCount shouldBe productReviewB.recommendCount + memberProductReviewB.reviewImages.size shouldBe 0 + + val memberProductReviewA = memberProductReviews[1] + memberProductReviewA.reviewId shouldBe productReviewA.id + memberProductReviewA.memberId shouldBe productReviewA.memberId + memberProductReviewA.createdAt shouldBe orderA.createdAt + memberProductReviewA.orderStatus shouldBe PURCHASE_CONFIRMED.name + memberProductReviewA.storeId shouldBe orderA.orderProduct.storeId + memberProductReviewA.storeId shouldBe orderA.orderProduct.storeId + memberProductReviewA.storeName shouldBe orderA.orderProduct.storeName + memberProductReviewA.productId shouldBe orderA.orderProduct.productId + memberProductReviewA.productName shouldBe orderA.orderProduct.productName + memberProductReviewA.productThumbnailUrl shouldBe orderA.orderProduct.thumbnailUrl + memberProductReviewA.quantity shouldBe orderA.orderProduct.quantity + memberProductReviewA.sex shouldBe orderA.orderProduct.sex.name + memberProductReviewA.deliveryMethod shouldBe orderA.orderProduct.deliveryMethod.name + memberProductReviewA.score shouldBe productReviewA.score.value + memberProductReviewA.content shouldBe productReviewA.content.value + memberProductReviewA.recommendCount shouldBe productReviewA.recommendCount + memberProductReviewA.reviewImages shouldBe listOf("imageA1", "imageA2") + } + } + } + afterContainer { dataCleaner.clean() }
Kotlin
์—ฌ๊ธฐ ์•„๋ž˜ memberProductReviews๊ฒ€์ฆํ•˜๋Š” ์ฝ”๋“œ๊ฐ€ ์กฐํผ ๊ธด๋ฐ ์Œ... ๋ฉ”์„œ๋“œ๋กœ ๋ถ„๋ฆฌํ•˜๋ฉด ์–ด๋–จ๊นŒ์š”?? valdiateMemberProductReview(memberProductReviewB, productReivewB, orderB);
@@ -6,6 +6,10 @@ import com.linecorp.kotlinjdsl.render.jpql.JpqlRenderer import com.petqua.common.domain.dto.CursorBasedPaging import com.petqua.common.util.createQuery import com.petqua.domain.member.Member +import com.petqua.domain.order.Order +import com.petqua.domain.order.OrderPayment +import com.petqua.domain.order.OrderProduct +import com.petqua.domain.product.dto.MemberProductReview import com.petqua.domain.product.dto.ProductReviewReadCondition import com.petqua.domain.product.dto.ProductReviewScoreWithCount import com.petqua.domain.product.dto.ProductReviewWithMemberResponse @@ -21,7 +25,7 @@ class ProductReviewCustomRepositoryImpl( override fun findAllByCondition( condition: ProductReviewReadCondition, - paging: CursorBasedPaging + paging: CursorBasedPaging, ): List<ProductReviewWithMemberResponse> { val query = jpql(ProductReviewDynamicJpqlGenerator) { @@ -69,4 +73,35 @@ class ProductReviewCustomRepositoryImpl( jpqlRenderer ) } + + override fun findMemberProductReviewBy( + memberId: Long, + paging: CursorBasedPaging, + ): List<MemberProductReview> { + val query = jpql(ProductReviewDynamicJpqlGenerator) { + selectNew<MemberProductReview>( + entity(ProductReview::class), + entity(Order::class), + entity(OrderPayment::class), + ).from( + entity(ProductReview::class), + join(Order::class).on( + path(ProductReview::memberId).eq(path(Order::memberId)) + .and(path(ProductReview::productId).eq(path(Order::orderProduct)(OrderProduct::productId))) + ), + join(OrderPayment::class).on(path(Order::id).eq(path(OrderPayment::orderId))) + ).whereAnd( + productReviewIdLt(paging.lastViewedId), + ).orderBy( + path(ProductReview::createdAt).desc(), + ) + } + + return entityManager.createQuery( + query, + jpqlRenderContext, + jpqlRenderer, + paging.limit + ) + } }
Kotlin
createdAt ๋Œ€์‹  id๋กœ ์ •๋ ฌํ•ด๋„ ๋ฌด๋ฐฉํ•œ ๊ฑฐ ๋งž์„๊นŒ์š”?? id๊ฐ€ ์ธ๋ฑ์Šค๋ผ ๋” ํšจ์œจ์ ์ผ ๊ฒƒ ๊ฐ™์•„์„œ์š”!
@@ -1,12 +1,14 @@ package com.petqua.application.product.review +import com.petqua.application.product.dto.MemberProductReviewReadQuery +import com.petqua.application.product.dto.MemberProductReviewResponse +import com.petqua.application.product.dto.MemberProductReviewsResponse import com.petqua.application.product.dto.ProductReviewReadQuery import com.petqua.application.product.dto.ProductReviewResponse import com.petqua.application.product.dto.ProductReviewStatisticsResponse import com.petqua.application.product.dto.ProductReviewsResponse import com.petqua.application.product.dto.UpdateReviewRecommendationCommand import com.petqua.common.domain.findByIdOrThrow -import com.petqua.domain.product.dto.ProductReviewWithMemberResponse import com.petqua.domain.product.review.ProductReview import com.petqua.domain.product.review.ProductReviewImage import com.petqua.domain.product.review.ProductReviewImageRepository @@ -42,7 +44,8 @@ class ProductReviewService( query.toCondition(), query.toPaging(), ) - val imagesByReview = getImagesByReview(reviewsByCondition) + val reviewIds = reviewsByCondition.map { it.id } + val imagesByReview = getImagesByReviewIds(reviewIds) val responses = reviewsByCondition.map { ProductReviewResponse(it, imagesByReview[it.id] ?: emptyList()) } @@ -59,12 +62,22 @@ class ProductReviewService( return ProductReviewsResponse.of(responses, query.limit) } - private fun getImagesByReview(reviewsByCondition: List<ProductReviewWithMemberResponse>): Map<Long, List<String>> { - val productReviewIds = reviewsByCondition.map { it.id } + private fun getImagesByReviewIds(productReviewIds: List<Long>): Map<Long, List<String>> { return productReviewImageRepository.findAllByProductReviewIdIn(productReviewIds).groupBy { it.productReviewId } .mapValues { it.value.map { image -> image.imageUrl } } } + fun readMemberProductReviews(query: MemberProductReviewReadQuery): MemberProductReviewsResponse { + val memberProductReviews = productReviewRepository.findMemberProductReviewBy(query.memberId, query.toPaging()) + val reviewIds = memberProductReviews.map { it.reviewId } + val imagesByReview = getImagesByReviewIds(reviewIds) + + val responses = memberProductReviews.map { + MemberProductReviewResponse(it, imagesByReview[it.reviewId] ?: emptyList()) + } + return MemberProductReviewsResponse.of(responses, query.limit) + } + @Transactional(readOnly = true) fun readReviewCountStatistics(productId: Long): ProductReviewStatisticsResponse { val reviewScoreWithCounts = productReviewRepository.findReviewScoresWithCount(productId)
Kotlin
ids๋ฅผ ๋ฐ›๊ฒŒ ๋ฐ”๊พธ๊ณ  ์žฌํ™œ์šฉ ๋„˜ ์ข‹๋„ค์š”!!
@@ -1,5 +1,6 @@ package com.petqua.presentation.product +import com.petqua.application.product.dto.MemberProductReviewsResponse import com.petqua.application.product.dto.ProductReviewStatisticsResponse import com.petqua.application.product.dto.ProductReviewsResponse import com.petqua.application.product.review.ProductReviewFacadeService @@ -9,6 +10,7 @@ import com.petqua.domain.auth.LoginMember import com.petqua.domain.auth.LoginMemberOrGuest import com.petqua.presentation.product.dto.CreateReviewRequest import com.petqua.presentation.product.dto.ReadAllProductReviewsRequest +import com.petqua.presentation.product.dto.ReadMemberProductReviewsRequest import com.petqua.presentation.product.dto.UpdateReviewRecommendationRequest import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.responses.ApiResponse @@ -63,14 +65,27 @@ class ProductReviewController( @PathVariable productId: Long, ): ResponseEntity<ProductReviewsResponse> { val responses = productReviewFacadeService.readAll( - request.toCommand( + request.toQuery( productId = productId, loginMemberOrGuest = loginMemberOrGuest, ) ) return ResponseEntity.ok(responses) } + @Operation(summary = "๋‚ด ํ›„๊ธฐ ์กฐํšŒ API", description = "๋‚ด๊ฐ€ ์ž‘์„ฑํ•œ ์ƒํ’ˆ์˜ ํ›„๊ธฐ๋ฅผ ์กฐํšŒํ•ฉ๋‹ˆ๋‹ค") + @ApiResponse(responseCode = "200", description = "์ƒํ’ˆ ํ›„๊ธฐ ์กฐ๊ฑด ์กฐํšŒ ์„ฑ๊ณต") + @SecurityRequirement(name = ACCESS_TOKEN_SECURITY_SCHEME_KEY) + @GetMapping("/product-reviews/me") + fun readMemberProductReviews( + @Auth loginMember: LoginMember, + request: ReadMemberProductReviewsRequest, + ): ResponseEntity<MemberProductReviewsResponse> { + val query = request.toQuery(loginMember) + val response = productReviewFacadeService.readMemberProductReviews(query) + return ResponseEntity.ok(response) + } + @Operation(summary = "์ƒํ’ˆ ํ›„๊ธฐ ํ†ต๊ณ„ ์กฐํšŒ API", description = "์ƒํ’ˆ์˜ ํ›„๊ธฐ ํ†ต๊ณ„๋ฅผ ์กฐํšŒํ•ฉ๋‹ˆ๋‹ค") @ApiResponse(responseCode = "200", description = "์ƒํ’ˆ ํ›„๊ธฐ ํ†ต๊ณ„ ์กฐํšŒ ์„ฑ๊ณต") @GetMapping("/products/{productId}/review-statistics")
Kotlin
URI ์ข‹๋„ค์šฉ๐Ÿ‘
@@ -2,13 +2,30 @@ package com.petqua.application.product.review import com.amazonaws.services.s3.AmazonS3 import com.ninjasquad.springmockk.SpykBean +import com.petqua.application.product.dto.MemberProductReviewReadQuery import com.petqua.application.product.dto.ProductReviewCreateCommand import com.petqua.common.domain.findByIdOrThrow +import com.petqua.domain.delivery.DeliveryMethod +import com.petqua.domain.member.MemberRepository +import com.petqua.domain.order.OrderNumber +import com.petqua.domain.order.OrderPayment +import com.petqua.domain.order.OrderPaymentRepository +import com.petqua.domain.order.OrderRepository +import com.petqua.domain.order.OrderStatus.PURCHASE_CONFIRMED +import com.petqua.domain.product.ProductRepository +import com.petqua.domain.product.option.Sex import com.petqua.domain.product.review.ProductReviewImageRepository import com.petqua.domain.product.review.ProductReviewRepository +import com.petqua.domain.store.StoreRepository import com.petqua.exception.product.review.ProductReviewException import com.petqua.exception.product.review.ProductReviewExceptionType import com.petqua.test.DataCleaner +import com.petqua.test.fixture.member +import com.petqua.test.fixture.order +import com.petqua.test.fixture.product +import com.petqua.test.fixture.productReview +import com.petqua.test.fixture.productReviewImage +import com.petqua.test.fixture.store import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.BehaviorSpec import io.kotest.matchers.shouldBe @@ -18,12 +35,18 @@ import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE import org.springframework.http.MediaType import org.springframework.mock.web.MockMultipartFile +import java.math.BigDecimal @SpringBootTest(webEnvironment = NONE) class ProductReviewFacadeServiceTest( private val productReviewFacadeService: ProductReviewFacadeService, private val productReviewRepository: ProductReviewRepository, private val productReviewImageRepository: ProductReviewImageRepository, + private val orderRepository: OrderRepository, + private val memberRepository: MemberRepository, + private val storeRepository: StoreRepository, + private val productRepository: ProductRepository, + private val orderPaymentRepository: OrderPaymentRepository, private val dataCleaner: DataCleaner, @SpykBean @@ -225,6 +248,151 @@ class ProductReviewFacadeServiceTest( } } + Given("์‚ฌ์šฉ์ž๊ฐ€ ๋ฆฌ๋ทฐ๋ฅผ ์ž‘์„ฑํ•œ ํ›„ ์ž์‹ ์˜ ๋ฆฌ๋ทฐ ๋‚ด์—ญ์„ ์กฐํšŒํ•  ๋•Œ") { + val member = memberRepository.save(member(nickname = "์ฟ ์•„")) + val store = storeRepository.save(store(name = "ํŽซ์ฟ ์•„")) + val productA = productRepository.save( + product( + name = "์ƒํ’ˆA", + storeId = store.id, + discountPrice = BigDecimal.ZERO, + reviewCount = 0, + reviewTotalScore = 0 + ) + ) + val productB = productRepository.save( + product( + name = "์ƒํ’ˆB", + storeId = store.id, + discountPrice = BigDecimal.ZERO, + reviewCount = 0, + reviewTotalScore = 0 + ) + ) + val orderA = orderRepository.save( + order( + orderNumber = OrderNumber.from("202402211607020ORDERNUMBER"), + memberId = member.id, + storeId = store.id, + storeName = store.name, + quantity = 1, + totalAmount = BigDecimal.ONE, + productId = productA.id, + productName = productA.name, + thumbnailUrl = productA.thumbnailUrl, + deliveryMethod = DeliveryMethod.SAFETY, + sex = Sex.FEMALE, + ) + ) + val orderB = orderRepository.save( + order( + orderNumber = OrderNumber.from("202402211607021ORDERNUMBER"), + memberId = member.id, + storeId = store.id, + storeName = store.name, + quantity = 1, + totalAmount = BigDecimal.ONE, + productId = productB.id, + productName = productB.name, + thumbnailUrl = productB.thumbnailUrl, + deliveryMethod = DeliveryMethod.SAFETY, + sex = Sex.FEMALE, + ) + ) + orderPaymentRepository.saveAll( + listOf( + OrderPayment( + orderId = orderA.id, + status = PURCHASE_CONFIRMED + ), + OrderPayment( + orderId = orderB.id, + status = PURCHASE_CONFIRMED + ) + ) + ) + + val productReviewA = productReviewRepository.save( + productReview( + productId = productA.id, + reviewerId = member.id, + score = 5, + recommendCount = 1, + hasPhotos = true, + content = "์ƒํ’ˆA ์ •๋ง ์ข‹์•„์š”!" + ) + ) + val productReviewB = productReviewRepository.save( + productReview( + productId = productB.id, + reviewerId = member.id, + score = 5, + recommendCount = 1, + hasPhotos = false, + content = "์ƒํ’ˆB ์ •๋ง ์ข‹์•„์š”!" + ) + ) + + productReviewImageRepository.saveAll( + listOf( + productReviewImage(imageUrl = "imageA1", productReviewId = productReviewA.id), + productReviewImage(imageUrl = "imageA2", productReviewId = productReviewA.id) + ) + ) + + When("ํšŒ์›์˜ Id๋ฅผ ์ž…๋ ฅํ•ด ์กฐํšŒํ•˜๋ฉด") { + val memberProductReviewsResponse = productReviewFacadeService.readMemberProductReviews( + MemberProductReviewReadQuery( + memberId = member.id + ) + ) + + Then("๋ฆฌ๋ทฐ ๋‚ด์—ญ์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค") { + val memberProductReviews = memberProductReviewsResponse.memberProductReviews + + memberProductReviews.size shouldBe 2 + + val memberProductReviewB = memberProductReviews[0] + memberProductReviewB.reviewId shouldBe productReviewB.id + memberProductReviewB.memberId shouldBe productReviewB.memberId + memberProductReviewB.createdAt shouldBe orderB.createdAt + memberProductReviewB.orderStatus shouldBe PURCHASE_CONFIRMED.name + memberProductReviewB.storeId shouldBe orderB.orderProduct.storeId + memberProductReviewB.storeId shouldBe orderB.orderProduct.storeId + memberProductReviewB.storeName shouldBe orderB.orderProduct.storeName + memberProductReviewB.productId shouldBe orderB.orderProduct.productId + memberProductReviewB.productName shouldBe orderB.orderProduct.productName + memberProductReviewB.productThumbnailUrl shouldBe orderB.orderProduct.thumbnailUrl + memberProductReviewB.quantity shouldBe orderB.orderProduct.quantity + memberProductReviewB.sex shouldBe orderB.orderProduct.sex.name + memberProductReviewB.deliveryMethod shouldBe orderB.orderProduct.deliveryMethod.name + memberProductReviewB.score shouldBe productReviewB.score.value + memberProductReviewB.content shouldBe productReviewB.content.value + memberProductReviewB.recommendCount shouldBe productReviewB.recommendCount + memberProductReviewB.reviewImages.size shouldBe 0 + + val memberProductReviewA = memberProductReviews[1] + memberProductReviewA.reviewId shouldBe productReviewA.id + memberProductReviewA.memberId shouldBe productReviewA.memberId + memberProductReviewA.createdAt shouldBe orderA.createdAt + memberProductReviewA.orderStatus shouldBe PURCHASE_CONFIRMED.name + memberProductReviewA.storeId shouldBe orderA.orderProduct.storeId + memberProductReviewA.storeId shouldBe orderA.orderProduct.storeId + memberProductReviewA.storeName shouldBe orderA.orderProduct.storeName + memberProductReviewA.productId shouldBe orderA.orderProduct.productId + memberProductReviewA.productName shouldBe orderA.orderProduct.productName + memberProductReviewA.productThumbnailUrl shouldBe orderA.orderProduct.thumbnailUrl + memberProductReviewA.quantity shouldBe orderA.orderProduct.quantity + memberProductReviewA.sex shouldBe orderA.orderProduct.sex.name + memberProductReviewA.deliveryMethod shouldBe orderA.orderProduct.deliveryMethod.name + memberProductReviewA.score shouldBe productReviewA.score.value + memberProductReviewA.content shouldBe productReviewA.content.value + memberProductReviewA.recommendCount shouldBe productReviewA.recommendCount + memberProductReviewA.reviewImages shouldBe listOf("imageA1", "imageA2") + } + } + } + afterContainer { dataCleaner.clean() }
Kotlin
+ ์กฐํšŒ ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•œ ๊ฒ€์ฆ์€ ๋ชจ๋“  ํ•„๋“œ๋ฅผ ํ•  ํ•„์š”๋Š” ์—†๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,22 @@ +package christmas.config; + +public enum ErrorMessage { + WRONG_DATE("์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค."), + WRONG_ORDER("์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค."), + OVER_MAX_ORDER("๋ฉ”๋‰ด๋Š” ํ•œ ๋ฒˆ์— ์ตœ๋Œ€ 20๊ฐœ๊นŒ์ง€๋งŒ ์ฃผ๋ฌธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค."), + ONLY_DRINK_ORDER("์Œ๋ฃŒ๋งŒ ์ฃผ๋ฌธํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + + private static final String PREFIX = "[ERROR]"; + private static final String SUFFIX = "๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + private static final String DELIMITER = " "; + + private final String message; + + ErrorMessage(String message) { + this.message = message; + } + + public String getMessage() { + return String.join(DELIMITER, PREFIX, message, SUFFIX); + } +}
Java
ํ•ด๋‹น ์—๋Ÿฌ๋ฉ”์‹œ์ง€๋Š” ์™œ enum์„ ์‚ฌ์šฉํ•˜์…จ๋‚˜์š”? ์ƒ์ˆ˜๋ฅผ ๋งŒ๋“œ๋Š” ๋ฐ ์ผ๋ฐ˜ ํด๋ž˜์Šค์™€ enum ํด๋ž˜์Šค๋ฅผ ์‚ฌ์šฉํ•˜์‹  ๊ธฐ์ค€์ด ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,57 @@ +package christmas.controller; + +import christmas.domain.*; +import christmas.dto.OrderDTO; +import christmas.util.IntParser; +import christmas.util.OrderParser; +import christmas.util.RetryExecutor; +import christmas.view.InputView; +import christmas.view.OutputView; + +import java.util.List; + +public class EventController { + private Bill bill; + private EventHandler eventHandler; + private final InputView inputView; + private final OutputView outputView; + + public EventController(InputView inputView, OutputView outputView) { + this.inputView = inputView; + this.outputView = outputView; + } + + public void run() { + outputView.printHelloMessage(); + RetryExecutor.execute(this::setBill, outputView::printErrorMessage); + RetryExecutor.execute(this::setOrder, error -> { + outputView.printErrorMessage(error); + bill.clearOrder(); + }); + printResult(); + } + + private void setBill() { + String input = inputView.inputDate().trim(); + bill = Bill.from(IntParser.parseIntOrThrow(input)); + eventHandler = EventHandler.from(bill); + } + + private void setOrder() { + String input = inputView.inputOrder(); + List<OrderDTO> orders = OrderParser.parseOrderOrThrow(input); + orders.forEach(it -> bill.add(Order.create(it.menuName(), it.count()))); + bill.validateOnlyDrink(); + } + + private void printResult() { + outputView.printEventPreviewTitle(bill.getDateValue()); + outputView.printOrder(bill.getAllOrders()); + outputView.printTotalPrice(bill.getTotalPrice()); + outputView.printGift(eventHandler.hasChampagneGift()); + outputView.printAllBenefit(eventHandler.getAllBenefit()); + outputView.printBenefitPrice(eventHandler.getTotalBenefitPrice()); + outputView.printAfterDiscountPrice(bill.getTotalPrice() - eventHandler.getTotalDiscountPrice()); + outputView.printBadge(Badge.getBadgeNameWithBenefitPrice(eventHandler.getTotalBenefitPrice())); + } +}
Java
์˜ค.. ์ด๋Ÿฐ ๋ฐฉ๋ฒ•์œผ๋กœ ์‚ฌ์šฉํ•˜๋Š” ํ•จ์ˆ˜ํ˜• ์ธํ„ฐํŽ˜์ด์Šค๋Š” ์ฒ˜์Œ ๋ณด๋Š” ๊ฒƒ ๊ฐ™์•„์š” ๋ฐฐ์šธ ๋ถ€๋ถ„์ด ๋งŽ๋„ค์š” ใ…  ๐Ÿ‘๐Ÿ‘
@@ -0,0 +1,26 @@ +package christmas.domain; + +import java.util.Arrays; + +public enum Badge { + SANTA("์‚ฐํƒ€", 20000), + TREE("ํŠธ๋ฆฌ", 10000), + STAR("๋ณ„", 5000), + NOTHING("์—†์Œ", 0); + + private final String badgeName; + private final int threshold; + + Badge(String badgeName, int threshold) { + this.badgeName = badgeName; + this.threshold = threshold; + } + + public static String getBadgeNameWithBenefitPrice(int benefitPrice) { + return Arrays.stream(Badge.values()) + .filter(it -> it.threshold <= benefitPrice) + .map(it -> it.badgeName) + .findFirst() + .orElse(NOTHING.badgeName); + } +}
Java
stream ์‚ฌ์šฉ์„ ์ž˜ํ•˜์‹œ๋Š” ๊ฒƒ ๊ฐ™์•„์š”! ํ˜น์‹œ ์–ด๋–ป๊ฒŒ ๊ณต๋ถ€ํ•˜๋ฉด ์ข‹์„์ง€... ํŒ์ด ์žˆ์œผ์‹ค๊นŒ์š”?
@@ -0,0 +1,94 @@ +package christmas.domain; + +import christmas.config.Constant; +import christmas.dto.OrderDTO; +import christmas.config.ErrorMessage; +import christmas.config.MenuType; + +import java.util.ArrayList; +import java.util.List; + +public class Bill implements CheckEventDate { + private final List<Order> orders = new ArrayList<>(); + private final Date date; + + private Bill(Date date) { + this.date = date; + } + + public static Bill from(int date) { + return new Bill(Date.from(date)); + } + + public Bill add(Order order) { + validateDuplicates(order); + orders.add(order); + validateMaxOrder(); + return this; + } + + private void validateDuplicates(Order newOrder) { + long duplicated = orders.stream() + .filter(it -> it.isSameMenu(newOrder)) + .count(); + if (duplicated != Constant.FILTER_CONDITION) { + throw new IllegalArgumentException(ErrorMessage.WRONG_ORDER.getMessage()); + } + } + + private void validateMaxOrder() { + if (Order.accumulateCount(orders) > Constant.MAX_ORDER) { + throw new IllegalArgumentException(ErrorMessage.OVER_MAX_ORDER.getMessage()); + } + } + + public void validateOnlyDrink() { + if (Order.accumulateCount(orders) == getTypeCount(MenuType.DRINK)) { + throw new IllegalArgumentException(ErrorMessage.ONLY_DRINK_ORDER.getMessage()); + } + } + + public void clearOrder() { + orders.clear(); + } + + public int getTotalPrice() { + return orders.stream() + .map(Order::getPrice) + .reduce(Constant.INIT_VALUE, Integer::sum); + } + + public int getTypeCount(MenuType type) { + return Order.accumulateCount(orders, type); + } + + public List<OrderDTO> getAllOrders() { + return orders.stream().map(Order::getOrder).toList(); + } + + // ์•„๋ž˜๋Š” Date ๊ด€๋ จ method + + @Override + public boolean isWeekend() { + return date.isWeekend(); + } + + @Override + public boolean isSpecialDay() { + return date.isSpecialDay(); + } + + @Override + public boolean isNotPassedChristmas() { + return date.isNotPassedChristmas(); + } + + @Override + public int timePassedSinceFirstDay() { + return date.timePassedSinceFirstDay(); + } + + public int getDateValue() { + return date.getDateValue(); + } +}
Java
ํ•ด๋‹น ๋ฆฌ์ŠคํŠธ๋ฅผ ํด๋ž˜์Šค๋กœ ๋งŒ๋“ค์–ด ์„ ์–ธ ํ•˜๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,75 @@ +package christmas.domain; + +import christmas.config.Menu; +import christmas.config.MenuType; + +import java.util.function.Function; +import java.util.function.Predicate; + +public enum Event { + CHRISTMAS( + "ํฌ๋ฆฌ์Šค๋งˆ์Šค ๋””๋ฐ์ด ํ• ์ธ", + true, + Bill::isNotPassedChristmas, + bill -> bill.timePassedSinceFirstDay() * 100 + 1000 + ), + WEEKDAY( + "ํ‰์ผ ํ• ์ธ", + true, + bill -> !bill.isWeekend(), + bill -> bill.getTypeCount(MenuType.DESSERT) * 2023 + ), + WEEKEND( + "์ฃผ๋ง ํ• ์ธ", + true, + Bill::isWeekend, + bill -> bill.getTypeCount(MenuType.MAIN) * 2023 + ), + SPECIAL( + "ํŠน๋ณ„ ํ• ์ธ", + true, + Bill::isSpecialDay, + bill -> 1000 + ), + CHAMPAGNE( + "์ฆ์ • ์ด๋ฒคํŠธ", + false, + bill -> bill.getTotalPrice() >= 120000, + bill -> Menu.CHAMPAGNE.getPrice() + ); + + private static final int ALL_EVENT_THRESHOLD = 10000; + + private final String eventName; + private final boolean isDiscount; + private final Predicate<Bill> condition; + private final Function<Bill, Integer> benefit; + + Event( + String eventName, + boolean isDiscount, + Predicate<Bill> condition, + Function<Bill, Integer> benefit + ) { + this.eventName = eventName; + this.isDiscount = isDiscount; + this.condition = condition; + this.benefit = benefit; + } + + public String getEventName() { + return eventName; + } + + public boolean isDiscount() { + return isDiscount; + } + + public boolean checkCondition(Bill bill) { + return condition.test(bill) && bill.getTotalPrice() >= ALL_EVENT_THRESHOLD; + } + + public int getBenefit(Bill bill) { + return benefit.apply(bill); + } +}
Java
์˜ค.. ํ• ์ธ ๋ฆฌ์ŠคํŠธ๋ฅผ enum ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ค์–ด ์„ ์–ธํ•œ ๊ฒƒ ๋˜๊ฒŒ ์ข‹์€ ์•„์ด๋””์–ด๋„ค์š” ๐Ÿ‘๐Ÿ‘
@@ -0,0 +1,38 @@ +package christmas.util; + +import christmas.config.ErrorMessage; + +public class IntParser { + private static final int MAX_STRING_LENGTH = 11; + + private IntParser() { + // ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ ๋ฐฉ์ง€ + } + + public static int parseIntOrThrow(String numeric) { + validateNumericStringLength(numeric); + long parsed = parseLongOrThrow(numeric); + validateIntRange(parsed); + return Integer.parseInt(numeric); + } + + private static long parseLongOrThrow(String numeric) { + try { + return Long.parseLong(numeric); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(ErrorMessage.WRONG_DATE.getMessage()); + } + } + + private static void validateNumericStringLength(String numeric) { + if (numeric.length() > MAX_STRING_LENGTH) { + throw new IllegalArgumentException(ErrorMessage.WRONG_DATE.getMessage()); + } + } + + private static void validateIntRange(long number) { + if (number > Integer.MAX_VALUE || number < Integer.MIN_VALUE) { + throw new IllegalArgumentException(ErrorMessage.WRONG_DATE.getMessage()); + } + } +}
Java
์ธ์Šคํ„ด์Šค ์ƒ์„ฑ ๋ฐฉ์ง€๋ผ๋Š” ๊ฒƒ์ด ๋ฌด์—‡์ธ์ง€ ์ž˜ ๋ชจ๋ฅด๊ฒ ๋Š”๋ฐ ๋นˆ ์ƒ์„ฑ์ž๋ฅผ ๋งŒ๋“ค์–ด ๋‘๋ฉด ๋ฌด์—‡์ด ์ข‹๋‚˜์š”..??
@@ -0,0 +1,91 @@ +package christmas.view; + +import christmas.dto.BenefitDTO; +import christmas.dto.OrderDTO; + +import java.util.List; + +public class OutputView { + private void printMessage(ViewMessage message) { + System.out.println(message.getMessage()); + } + + private void printFormat(ViewMessage message, Object... args) { + System.out.printf(message.getMessage(), args); + newLine(); + } + + private void printTitle(ViewTitle title) { + System.out.println(title.getTitle()); + } + + public void printHelloMessage() { + printMessage(ViewMessage.HELLO); + } + + public void printEventPreviewTitle(int date) { + printFormat(ViewMessage.EVENT_PREVIEW_TITLE, date); + newLine(); + } + + public void printOrder(List<OrderDTO> orders) { + printTitle(ViewTitle.ORDER_MENU); + orders.forEach(it -> printFormat(ViewMessage.ORDER_FORMAT, it.menuName(), it.count())); + newLine(); + } + + public void printTotalPrice(int price) { + printTitle(ViewTitle.TOTAL_PRICE); + printFormat(ViewMessage.PRICE_FORMAT, price); + newLine(); + } + + public void printGift(boolean hasGift) { + printTitle(ViewTitle.GIFT_MENU); + if (hasGift) { + printMessage(ViewMessage.CHAMPAGNE); + newLine(); + return; + } + printMessage(ViewMessage.NOTHING); + newLine(); + } + + public void printAllBenefit(List<BenefitDTO> benefits) { + printTitle(ViewTitle.BENEFIT_LIST); + if (benefits.isEmpty()) { + printMessage(ViewMessage.NOTHING); + newLine(); + return; + } + benefits.forEach(it -> printFormat(ViewMessage.BENEFIT_FORMAT, it.EventName(), it.price())); + newLine(); + } + + public void printBenefitPrice(int price) { + printTitle(ViewTitle.BENEFIT_PRICE); + printFormat(ViewMessage.PRICE_FORMAT, -price); + newLine(); + } + + public void printAfterDiscountPrice(int price) { + printTitle(ViewTitle.AFTER_DISCOUNT_PRICE); + printFormat(ViewMessage.PRICE_FORMAT, price); + newLine(); + } + + public void printBadge(String badge) { + printTitle(ViewTitle.BADGE); + System.out.println(badge); + } + + public void printErrorMessage(IllegalArgumentException error) { + newLine(); + System.out.println(error.getMessage()); + newLine(); + } + + public void newLine() { + System.out.println(); + } +}
Java
์ƒˆ๋กœ์šด ๋ผ์ธ์„ ๋งŒ๋“ค๋•Œ๋Š” System.lineSeperator()๋ฅผ ์ถ”์ฒœ ํ•ด์ฃผ์‹œ๋”๋ผ๊ตฌ์š”. ์ฐธ๊ณ ํ•˜์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,145 @@ +package christmas.domain; + +import christmas.dto.OrderDTO; +import christmas.config.ErrorMessage; +import christmas.config.MenuType; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.List; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +public class BillTest { + @DisplayName("์ž˜๋ชป๋œ date ๊ฐ’ ์‚ฌ์šฉ ์‹œ ์˜ˆ์™ธ ๋ฐœ์ƒ") + @ParameterizedTest + @ValueSource(ints = {-5, 0, 32, 75}) + void checkCreateFromWrongDate(int date) { + assertThatThrownBy(() -> Bill.from(date)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(ErrorMessage.WRONG_DATE.getMessage()); + } + + @DisplayName("add ๋™์ž‘ ํ™•์ธ") + @Test + void checkAddMethod() { + Bill bill = Bill.from(1) + .add(Order.create("์‹œ์ €์ƒ๋Ÿฌ๋“œ", 3)) + .add(Order.create("ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", 1)) + .add(Order.create("์ œ๋กœ์ฝœ๋ผ", 2)); + + List<OrderDTO> answer = List.of( + new OrderDTO("์‹œ์ €์ƒ๋Ÿฌ๋“œ", 3), + new OrderDTO("ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", 1), + new OrderDTO("์ œ๋กœ์ฝœ๋ผ", 2) + ); + + assertThat(bill.getAllOrders()).isEqualTo(answer); + } + + @DisplayName("์ค‘๋ณต๋œ ๋ฉ”๋‰ด๋ฅผ ์ž…๋ ฅ์‹œ ์˜ˆ์™ธ ๋ฐœ์ƒ") + @Test + void checkDuplicatedMenu() { + assertThatThrownBy(() -> Bill.from(1) + .add(Order.create("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", 2)) + .add(Order.create("๋ฐ”๋น„ํ๋ฆฝ", 1)) + .add(Order.create("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", 3)) + ).isInstanceOf(IllegalArgumentException.class).hasMessage(ErrorMessage.WRONG_ORDER.getMessage()); + } + + @DisplayName("๋ฉ”๋‰ด๊ฐ€ 20๊ฐœ๋ฅผ ์ดˆ๊ณผํ•˜๋Š” ๊ฒฝ์šฐ ์˜ˆ์™ธ ๋ฐœ์ƒ") + @ParameterizedTest + @MethodSource("overedOrder") + void checkOverOrder(List<Order> orders) { + Bill bill = Bill.from(1); + + assertThatThrownBy(() -> orders.forEach(bill::add)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(ErrorMessage.OVER_MAX_ORDER.getMessage()); + } + + static Stream<Arguments> overedOrder() { + return Stream.of( + Arguments.of(List.of( + Order.create("ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", 7), + Order.create("์ œ๋กœ์ฝœ๋ผ", 15) + )), + Arguments.of(List.of( + Order.create("์•„์ด์Šคํฌ๋ฆผ", 25) + )) + ); + } + + @DisplayName("clearOrder ๋™์ž‘ ํ™•์ธ") + @Test + void checkClearOrder() { + Bill bill = Bill.from(1) + .add(Order.create("์‹œ์ €์ƒ๋Ÿฌ๋“œ", 3)) + .add(Order.create("ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", 1)) + .add(Order.create("์ œ๋กœ์ฝœ๋ผ", 2)); + bill.clearOrder(); + assertThat(bill.getAllOrders()).isEqualTo(List.of()); + } + + @DisplayName("getTotalPrice ๋™์ž‘ ํ™•์ธ") + @Test + void checkTotalPrice() { + Bill bill = Bill.from(1) + .add(Order.create("ํƒ€ํŒŒ์Šค", 2)) + .add(Order.create("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 1)) + .add(Order.create("์ œ๋กœ์ฝœ๋ผ", 2)); + assertThat(bill.getTotalPrice()).isEqualTo(72000); + } + + @DisplayName("getTypeCount ๋™์ž‘ ํ™•์ธ") + @ParameterizedTest + @MethodSource("typedBill") + void checkTypeCount(Bill bill, MenuType type, int answer) { + assertThat(bill.getTypeCount(type)).isEqualTo(answer); + } + + static Stream<Arguments> typedBill() { + return Stream.of( + Arguments.of( + Bill.from(1) + .add(Order.create("์–‘์†ก์ด์ˆ˜ํ”„", 3)) + .add(Order.create("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 1)) + .add(Order.create("๋ฐ”๋น„ํ๋ฆฝ", 2)), + MenuType.MAIN, + 3 + ), + Arguments.of( + Bill.from(1) + .add(Order.create("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 2)) + .add(Order.create("์ดˆ์ฝ”์ผ€์ดํฌ", 2)) + .add(Order.create("์•„์ด์Šคํฌ๋ฆผ", 3)) + .add(Order.create("์ œ๋กœ์ฝœ๋ผ", 7)), + MenuType.DESSERT, + 5 + ) + ); + } + + @DisplayName("getDateValue ๋™์ž‘ ํ™•์ธ") + @ParameterizedTest + @ValueSource(ints = {1, 17, 25, 31}) + void checkDateValue(int date) { + assertThat(Bill.from(date).getDateValue()).isEqualTo(date); + } + + @DisplayName("์Œ๋ฃŒ๋งŒ ์ฃผ๋ฌธํ•œ ๊ฒฝ์šฐ ์˜ˆ์™ธ ๋ฐœ์ƒ") + @Test + void checkOnlyDrinkOrder() { + assertThatThrownBy(() -> Bill.from(1) + .add(Order.create("์ œ๋กœ์ฝœ๋ผ", 3)) + .add(Order.create("๋ ˆ๋“œ์™€์ธ", 1)) + .validateOnlyDrink() + ).isInstanceOf(IllegalArgumentException.class).hasMessage(ErrorMessage.ONLY_DRINK_ORDER.getMessage()); + } +}
Java
isInstanceOf์™€ hasMessage๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ข€ ๋” ๊ผผ๊ผผํ•œ ํ…Œ์ŠคํŠธ๋ฅผ ํ•  ์ˆ˜ ์žˆ๊ตฐ์š”! ๋ฐฐ์›Œ ๊ฐ‘๋‹ˆ๋‹น ๐Ÿ‘๐Ÿ‘
@@ -0,0 +1,22 @@ +package christmas.config; + +public enum ErrorMessage { + WRONG_DATE("์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค."), + WRONG_ORDER("์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค."), + OVER_MAX_ORDER("๋ฉ”๋‰ด๋Š” ํ•œ ๋ฒˆ์— ์ตœ๋Œ€ 20๊ฐœ๊นŒ์ง€๋งŒ ์ฃผ๋ฌธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค."), + ONLY_DRINK_ORDER("์Œ๋ฃŒ๋งŒ ์ฃผ๋ฌธํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + + private static final String PREFIX = "[ERROR]"; + private static final String SUFFIX = "๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + private static final String DELIMITER = " "; + + private final String message; + + ErrorMessage(String message) { + this.message = message; + } + + public String getMessage() { + return String.join(DELIMITER, PREFIX, message, SUFFIX); + } +}
Java
์‚ฌ์‹ค ์ €๋„ ์ƒ์ˆ˜๋ฅผ ์ฒ˜๋ฆฌํ•  ๋•Œ `enum`์„ ์‚ฌ์šฉํ• ์ง€ `class`๋ฅผ ์‚ฌ์šฉํ• ์ง€ ๊ณ ๋ฏผ์ด ๋งŽ์•˜์Šต๋‹ˆ๋‹ค. ์–ด๋–ค ๊ธฐ์ค€์„ ์„ธ์›Œ์•ผ ํ• ์ง€๋„ ์Šค์Šค๋กœ ํ™•๋ฆฝํ•˜์ง€ ๋ชปํ–ˆ๊ตฌ์š”. ๊ทธ๋ž˜์„œ ์šฐ์„ ์€ ์•„๋ฌด๋Ÿฐ ๊ธฐ๋Šฅ ์—†์ด ์ƒ์ˆ˜๊ฐ’๋งŒ ์ €์žฅํ•˜๋Š” ๊ฒฝ์šฐ๋Š” `class`๋ฅผ ์‚ฌ์šฉํ•˜๊ณ , ์•ฝ๊ฐ„์˜ ๊ธฐ๋Šฅ์ด๋ผ๋„ ํ•จ๊ป˜ ์‚ฌ์šฉํ•œ๋‹ค๋ฉด `enum`์„ ์‚ฌ์šฉํ•˜๋ ค๊ณ  ํ•ด๋ดค์Šต๋‹ˆ๋‹ค. ์—ฌ๊ธฐ `ErrorMessage`์—์„œ๋Š” ๊ณตํ†ต์ ์œผ๋กœ ์‚ฌ์šฉ๋˜๋Š” prefix์™€ suffix๋ฅผ `getMessage()`๋ฉ”์„œ๋“œ์—์„œ ํ•จ๊ป˜ ํ•ฉ์ณ์„œ ๋ฐ˜ํ™˜ํ•˜๋„๋ก ๊ตฌ์ƒํ–ˆ๊ธฐ ๋•Œ๋ฌธ์— `enum`์„ ์‚ฌ์šฉํ•ด๋ดค์Šต๋‹ˆ๋‹ค. ์‚ฌ์‹ค `class`๋กœ ์‚ฌ์šฉํ•ด๋„ ๋ฌด๋ฐฉํ• ๊ฑฐ ๊ฐ™๋„ค์š”. ๐Ÿ˜‚