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`๋ก ์ฌ์ฉํด๋ ๋ฌด๋ฐฉํ ๊ฑฐ ๊ฐ๋ค์. ๐ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.