code stringlengths 41 34.3k | lang stringclasses 8
values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,25 @@
+package christmas.domain;
+
+import christmas.validator.Validator;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class Order {
+
+ private Map<Menu, Integer> orderedItems;
+
+ private Order(Map<Menu, Integer> orderedItems ) {
+ this.orderedItems = orderedItems;
+ }
+
+ public static Order from(Map<Menu, Integer> orderMap) {
+// Map<Menu, Integer> orderMap = parseOrder(order);
+ return new Order(orderMap);
+ }
+
+ public Map<Menu, Integer> getOrderedItems() {
+ return orderedItems;
+ }
+} | Java | 왜 같은 메서드가 두개일까요? |
@@ -0,0 +1,20 @@
+package christmas.domain;
+
+import christmas.validator.Validator;
+
+public class Reservation {
+ private final int date;
+
+ private Reservation(int date) {
+ Validator.isInRange(date);
+ this.date = date;
+ }
+
+ public static Reservation from(int date) {
+ return new Reservation(date);
+ }
+
+ public int getDate() {
+ return date;
+ }
+} | Java | 여기도 그렇네요 어떤 이유로 생성자를 private으로 막아두시고 static 메서드를 사용하셨을까요 |
@@ -0,0 +1,171 @@
+package christmas.domain;
+
+import static christmas.domain.DiscountType.*;
+
+import java.util.Map;
+
+public class Result {
+
+ private int totalBeforeDiscount;
+ private int serviceMenu;
+ private int dDayDiscount;
+ private int weekdayDiscount;
+ private int weekendDiscount;
+ private int specialDiscount;
+ private int totalBenefit;
+ private int totalAfterBenefit;
+ private String badge = EventBadge.NONE.getDescription();
+
+ private Map<Menu, Integer> orderedItems;
+ private int date;
+
+ private Result(Map<Menu, Integer> orderedItems, int date) {
+ this.orderedItems = orderedItems;
+ this.date = date;
+ calculateTotalBeforeDiscount(); // 할인 전 총주문 금액
+ checkEventExecutionConditions();
+ calculateETCEvents();
+ }
+
+ private void calculateETCEvents() {
+ calculateTotalAfterBenefit();
+ calculateEventBadge();
+ }
+
+ private void checkEventExecutionConditions() {
+ if (totalBeforeDiscount >= MIN_EVENT_CONDITION.getType()) {
+ calculateAllEvents();
+ }
+ }
+
+ private void calculateAllEvents() {
+ calculateServiceMenu(); // 증정메뉴
+ calculateBenefit();
+ calculateWeekday();
+ calculateWeekend();
+ calculateSpecialDay();
+ calculateAllBenefit();
+ }
+
+ public static Result from(Map<Menu, Integer> orderedItems, int date) {
+ return new Result(orderedItems, date);
+ }
+
+ public void calculateTotalBeforeDiscount() {
+ for (Map.Entry<Menu, Integer> entry : orderedItems.entrySet()) {
+ Menu menu = entry.getKey();
+ int quantity = entry.getValue();
+ int menuPrice = menu.getPrice();
+ int subtotal = menuPrice * quantity;
+
+ totalBeforeDiscount += subtotal;
+ }
+ }
+
+ public void calculateServiceMenu() {
+ if (totalBeforeDiscount >= CHAMPAGNE_CONDITION.getType()) {
+ serviceMenu = SERVICE_MENU_CONDITION.getType();
+ }
+ }
+
+ public void calculateBenefit() {
+ if (date <= DDAY_CONDITION.getType()) {
+ dDayDiscount = BASE_AMOUNT.getType() + (date * DAY_BONUS.getType());
+ }
+ }
+
+ public void calculateWeekday() {
+ if (Calendar.isWeekday(date)) {
+ int totalDessertCount = INIT_COUNT.getType(); // 디저트 카테고리의 총 개수
+
+ for (Map.Entry<Menu, Integer> entry : orderedItems.entrySet()) {
+ Menu menu = entry.getKey();
+ int quantity = entry.getValue();
+
+ // 디저트 카테고리인 경우 개수 합산
+ if (menu.isDessert()) {
+ totalDessertCount += quantity;
+ }
+ }
+ weekdayDiscount = totalDessertCount * SPECIALDAY_CONDITION.getType();
+ }
+ }
+
+ public void calculateWeekend() {
+ if (Calendar.isWeekend(date)) {
+ int totalMainCount = INIT_COUNT.getType();
+
+ for (Map.Entry<Menu, Integer> entry : orderedItems.entrySet()) {
+ Menu menu = entry.getKey();
+ int quantity = entry.getValue();
+
+ // 메인 요리인 경우 개수 합산
+ if (menu.isMain()) {
+ totalMainCount += quantity;
+ }
+ }
+ weekendDiscount = totalMainCount * SPECIALDAY_CONDITION.getType();
+ }
+ }
+
+ public void calculateSpecialDay() {
+ if (Calendar.isSpecialDay(date)) {
+ specialDiscount = SPECIAL_DISCOUNT.getType();
+ }
+ }
+
+ public void calculateAllBenefit() {
+ totalBenefit = dDayDiscount + weekdayDiscount + weekendDiscount + specialDiscount + (serviceMenu * CHAMPAGNE.getType());
+ }
+
+ public void calculateTotalAfterBenefit() {
+ totalAfterBenefit = totalBeforeDiscount - (totalBenefit - (serviceMenu * CHAMPAGNE.getType()));
+ }
+
+ public void calculateEventBadge() {
+ EventBadge badge = EventBadge.getBadge(totalBenefit);
+ if (badge != null) {
+ this.badge = badge.getDescription();
+ }
+ }
+
+ public int getTotalBeforeDiscount() {
+ return totalBeforeDiscount;
+ }
+
+ public int getServiceMenu() {
+ return serviceMenu;
+ }
+
+ public int getdDayDiscount() {
+ return dDayDiscount;
+ }
+
+ public int getWeekdayDiscount() {
+ return weekdayDiscount;
+ }
+
+ public int getWeekendDiscount() {
+ return weekendDiscount;
+ }
+
+ public int getSpecialDiscount() {
+ return specialDiscount;
+ }
+
+ public int getTotalBenefit() {
+ return totalBenefit;
+ }
+
+ public int getTotalAfterBenefit() {
+ return totalAfterBenefit;
+ }
+
+ public String getBadge() {
+ return badge;
+ }
+
+ public int getDate() {
+ return date;
+ }
+} | Java | 한 객체에 너무 많은 필드를 선언했는데 책임을 분리할 수 있지 않을까요? |
@@ -0,0 +1,150 @@
+package christmas.validator;
+
+import christmas.domain.Menu;
+import christmas.exception.ErrorMessage;
+import christmas.exception.ValidatorException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class Validator {
+ private static final String DELIMITER = ",";
+ private static final int FIRST_DAY = 1;
+ private static final int LAST_DAY = 31;
+ private static final int MAX_MENU_COUNT = 20;
+ private static final int MIN_MUST_COUNT = 1;
+ private static final int TRUE = 1;
+ private static final int FALSE = 0;
+ public static int convertDateStringToInt(String input) {
+ try {
+ isNumeric(input);
+ return Integer.parseInt(input);
+ } catch (NumberFormatException exception) {
+ throw ValidatorException.of(ErrorMessage.INVALID_DATE, exception);
+ }
+ }
+
+ public static int convertOrderStringToInt(String input) {
+ try {
+ isNumeric(input);
+ return Integer.parseInt(input);
+ } catch (NumberFormatException exception) {
+ throw ValidatorException.of(ErrorMessage.INVALID_ORDER, exception);
+ }
+ }
+
+ private static boolean isNumeric(String input) {
+ return input.matches("\\d+");
+ }
+
+ public static void isInRange(int date) {
+ if (date < FIRST_DAY || date > LAST_DAY) {
+ throw ValidatorException.from(ErrorMessage.INVALID_ORDER);
+ }
+ }
+
+ public static boolean isValidOrderFormat(String order) {
+ try {
+ String regex = "([\\w가-힣]+-\\d+,)*[\\w가-힣]+-\\d+";
+ Pattern pattern = Pattern.compile(regex);
+ Matcher matcher = pattern.matcher(order);
+ return matcher.matches();
+ } catch (IllegalArgumentException exception) {
+ throw ValidatorException.of(ErrorMessage.INVALID_ORDER, exception);
+ }
+ }
+
+
+ public static Map<Menu, Integer> parseOrder(String order) {
+ try {
+ Map<Menu, Integer> orderMap = new HashMap<>();
+ Set<Menu> uniqueMenus = new HashSet<>();
+ String[] items = order.split(",");
+ int count = 0;
+ int beverageFlag = FALSE;
+ for (String item : items) {
+ String[] parts = item.split("-");
+ validateNonNumericString(parts[0]); // 처음 들어온 값이 숫자면 에러
+ Menu menu = getMenuByName(parts[0]);
+ if (!menu.isBeverage()) {
+ beverageFlag = TRUE;
+ }
+ isDuplicate(uniqueMenus, menu);
+ if (parts.length == 2) {
+ int quantity = convertOrderStringToInt(parts[1]);
+ isMinCount(quantity);
+ count += quantity;
+ orderMap.put(menu, quantity);
+ }
+ }
+ isOnlyBeverageOrder(beverageFlag);
+ isMaxCount(count);
+ return orderMap;
+ } catch (IllegalArgumentException exception) {
+ throw ValidatorException.of(ErrorMessage.INVALID_ORDER, exception);
+ }
+ }
+
+ private static void isOnlyBeverageOrder(int beverageFlag) {
+ if (beverageFlag == FALSE) {
+ throw ValidatorException.from(ErrorMessage.INVALID_ORDER);
+ }
+ }
+
+ private static void isDuplicate(Set<Menu> uniqueMenus, Menu menu) {
+ if (!uniqueMenus.add(menu)) {
+ throw ValidatorException.from(ErrorMessage.INVALID_ORDER);
+ }
+ }
+
+ private static void isMinCount(int quantity) {
+ if (quantity < MIN_MUST_COUNT) {
+ throw ValidatorException.from(ErrorMessage.INVALID_ORDER);
+ }
+ }
+
+ private static void isMaxCount(int count) {
+ if (count > MAX_MENU_COUNT) {
+ throw ValidatorException.from(ErrorMessage.INVALID_ORDER);
+ }
+ }
+
+ public static void validateNonNumericString(String input) {
+ if (isNumeric(input)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_ORDER.getMessage());
+ }
+ }
+
+ public static Menu getMenuByName(String menuName) {
+ for (Menu menu : Menu.values()) {
+ if (menu.name().equalsIgnoreCase(menuName)) {
+ return menu;
+ }
+ }
+ throw new IllegalArgumentException(ErrorMessage.INVALID_ORDER.getMessage());
+ }
+
+
+ public static void validateContainWhiteSpace(String input) {
+ if (hasWhiteSpace(input)) {
+ throw ValidatorException.from(ErrorMessage.CONTAIN_WHITESPACE);
+ }
+ }
+
+ public static void validateEndsWithDelimiter(String input) {
+ if (isEndsWithDelimiter(input)) {
+ throw ValidatorException.from(ErrorMessage.ENDS_WITH_DELIMITER);
+ }
+ }
+
+ private static boolean hasWhiteSpace(String input) {
+ return input.chars().anyMatch(Character::isWhitespace);
+ }
+
+ private static boolean isEndsWithDelimiter(String input) {
+ return input.endsWith(DELIMITER);
+ }
+} | Java | validator라는 static 메서드만 가지고 있는 클래스를 만드신 이유가 궁금합니다 |
@@ -0,0 +1,87 @@
+package christmas.domain;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+class CalendarTest {
+
+ @DisplayName("평일에 해당하는 날짜를 입력했을 때 검증")
+ @Test
+ public void testIsWeekday() {
+ // Given
+ int weekday = 5;
+
+ // When
+ boolean result = Calendar.isWeekday(weekday);
+
+ // Then
+ assertTrue(result, "평일이 맞음");
+ }
+
+ @DisplayName("평일에 해당하지 않는 날짜를 입력했을 때 검증")
+ @Test
+ public void testIsNotWeekday() {
+ // Given
+ int weekday = 9;
+
+ // When
+ boolean result = Calendar.isWeekday(weekday);
+
+ // Then
+ assertFalse(result, "평일이 아님");
+ }
+
+ @DisplayName("주말에 해당하는 날짜를 입력했을 때 검증")
+ @Test
+ public void testIsWeekend() {
+ // Given
+ int weekend = 9;
+
+ // When
+ boolean result = Calendar.isWeekend(weekend);
+
+ // Then
+ assertTrue(result, "주말이 맞음");
+ }
+
+ @DisplayName("주말에 해당하지 않는 날짜를 입력했을 때 검증")
+ @Test
+ public void testIsNotWeekend() {
+ // Given
+ int weekend = 3;
+
+ // When
+ boolean result = Calendar.isWeekend(weekend);
+
+ // Then
+ assertFalse(result, "주말이 아님");
+ }
+
+ @DisplayName("특별한 날에 해당하는 날짜를 입력했을 때 검증")
+ @Test
+ public void testIsSpecialDay() {
+ // Given
+ int specialDay = 25;
+
+ // When
+ boolean result = Calendar.isSpecialDay(specialDay);
+
+ // Then
+ assertTrue(result, "특별한 날");
+ }
+
+ @DisplayName("특별한 날에 해당하지 않는 날짜를 입력했을 때 검증")
+ @Test
+ public void testIsNotSpecialDay() {
+ // Given
+ int specialDay = 19;
+
+ // When
+ boolean result = Calendar.isSpecialDay(specialDay);
+
+ // Then
+ assertFalse(result, "특별한 날");
+ }
+}
\ No newline at end of file | Java | assertJ 라이브러리를 사용하시는 것을 추천드립니다 |
@@ -0,0 +1,88 @@
+package christmas.domain;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+class MenuTest {
+
+ @DisplayName("양송이 수프 가격 동일한지 검증")
+ @Test
+ public void testGetPrice() {
+ // Given
+ Menu menu = Menu.양송이수프;
+
+ // When
+ int price = menu.getPrice();
+
+ // Then
+ assertEquals(6_000, price, "양송이수프의 가격이 같음");
+ }
+
+ @DisplayName("음료인지 검증")
+ @Test
+ public void testIsBeverage() {
+ // Given
+ Menu cola = Menu.제로콜라;
+ Menu wine = Menu.레드와인;
+ Menu champagne = Menu.샴페인;
+ Menu pasta = Menu.크리스마스파스타;
+
+ // Then
+ assertTrue(cola.isBeverage(), "제로콜라는 음료수");
+ assertTrue(wine.isBeverage(), "레드와인은 음료수");
+ assertTrue(champagne.isBeverage(), "샴페인은 음료수");
+ assertFalse(pasta.isBeverage(), "크리스마스파스타는 음료수가 아님");
+ }
+
+ @DisplayName("디저트인지 검증")
+ @Test
+ public void testIsDessert() {
+ // Given
+ Menu cake = Menu.초코케이크;
+ Menu iceCream = Menu.아이스크림;
+ Menu pasta = Menu.크리스마스파스타;
+
+ // Then
+ assertTrue(cake.isDessert(), "초코케이크는 디저트");
+ assertTrue(iceCream.isDessert(), "아이스크림은 디저트");
+ assertFalse(pasta.isDessert(), "크리스마스파스타는 디저트가 아님");
+ }
+
+ @DisplayName("메인요리인지 검증")
+ @Test
+ public void testIsMain() {
+ // Given
+ Menu steak = Menu.티본스테이크;
+ Menu ribs = Menu.바비큐립;
+ Menu pasta = Menu.크리스마스파스타;
+ Menu soup = Menu.양송이수프;
+
+ // Then
+ assertTrue(steak.isMain(), "티본스테이크는 메인요리");
+ assertTrue(ribs.isMain(), "바비큐립은 메인요리");
+ assertTrue(pasta.isMain(), "크리스마스파스타는 메인요리");
+ assertFalse(soup.isMain(), "양송이수프는 메인요리가 아님");
+ }
+
+ @DisplayName("주문 메뉴가 메뉴에 포함되어 있는지 검증")
+ @Test
+ public void testContains_ValidItem() {
+ // Given
+ String itemName = "아이스크림";
+
+ // Then
+ assertTrue(Menu.contains(itemName), "메뉴에 아이스크림이 있어야 함");
+ }
+
+ @DisplayName("주문 메뉴가 메뉴에 포함되어 있지 않은지 검증")
+ @Test
+ public void testContains_InvalidItem() {
+ // Given
+ String itemName = "피자";
+
+ // Then
+ assertFalse(Menu.contains(itemName), "메뉴에 피자가 없어야 함");
+ }
+}
\ No newline at end of file | Java | softAssertion이나 assertAll에 대해 알아보시면 좋을 것 같아요 |
@@ -0,0 +1,241 @@
+# 미션 - 크리스마스 프로모션 🎄
+
+## ✅ 기능 목록
+
+### 1. 게임 시작
+
+- [X] 식당 예상 방문 날짜를 입력 받는다.
+ - [X] 방문할 날짜는 1 이상 31 이하의 숫자만 입력 받는다.
+ - [X] 잘못된 값을 입력한 경우 예외 처리한다.
+
+- [X] 고객에게 안내할 이벤트 주의 사항을 출력한다.
+
+- [X] 주문할 메뉴와 개수를 입력 받는다.
+ - [X] 메뉴판에 없는 메뉴를 입력 시 예외 처리한다.
+ - [X] 메뉴의 개수는 1 이상의 숫자가 아닐 경우 예외 처리한다.
+ - [X] 메뉴는 한 번에 최대 20개까지만 주문할 수 있다.
+ - [X] 음료만 주문 시, 주문할 수 없다.
+ - [X] 중복 메뉴를 입력한 경우 예외 처리한다.
+ - [X] 총 주문 금액 10,000원 이상이 아닐 경우 이벤트를 적용하지 않는다.
+
+### 2. 게임 진행
+
+- [X] 예상 방문 날짜, 메뉴, 개수를 계산하고 다음 이벤트를 검사한다.
+ - [X] 크리스마스 디데이 할인
+ - [X] 평일 할인(일요일~목요일)
+ - [X] 주말 할인(금요일, 토요일)
+ - [X] 특별 할인
+ - [X] 증정 이벤트
+ - [X] 이벤트 기간
+
+- [X] 혜택 금액에 따른 이벤트 배지 부여
+ - [X] 5천 원 이상: 별
+ - [X] 1만 원 이상: 트리
+ - [X] 2만 원 이상: 산타
+
+### 3. 게임 종료
+
+- [X] 식당에 방문할 날짜와 메뉴를 미리 선택하면 이벤트 플래너가 아래의 항목들을 출력한다.
+ - [X] 주문 메뉴
+ - [X] 주문 메뉴의 출력 순서는 자유롭게 출력한다.
+ - [X] 할인 전 총주문 금액
+ - [X] 증정 메뉴
+ - [X] 증정 이벤트에 해당하지 않는 경우, 증정 메뉴 “없음”으로 출력한다.
+ - [X] 혜택 내역
+ - [X] 고객에게 적용된 이벤트 내역만 출력한다.
+ - [X] 적용된 이벤트가 하나도 없다면 혜택 내역 “없음”으로 출력한다.
+ - [X] 여러 개의 이벤트가 적용된 경우, 출력 순서는 자유롭게 출력한다.
+ - [X] 총혜택 금액
+ - [X] 총혜택 금액에 따른 이벤트 배지의 이름을 다르게 출력한다.
+ - [X] 총혜택 금액 = 할인 금액의 합계 + 증정 메뉴의 가격
+ - [X] 할인 후 예상 결제 금액
+ - [X] 할인 후 예상 결제 금액 = 할인 전 총주문 금액 - 할인 금액
+ - [X] 증정 이벤트에 포함된 금액은 할인 후 예상 결제 금액에 포함시키지 않는다.
+ - [X] 12월 이벤트 배지 내용
+ - [X] 이벤트 배지가 부여되지 않는 경우, “없음”으로 출력한다.
+
+### 4. 예외
+
+- 사용자가 잘못된 값을 입력할 경우 `IllegalArgumentException`를 발생시키고, "[ERROR]"로 시작하는 에러 메시지를 출력 후 **그 부분부터 입력을 다시 받는다.**
+ - `Exception`이 아닌 `IllegalArgumentException`, `IllegalStateException` 등과 같은 명확한 유형을 처리한다.
+ - 예외 상황 시 에러 문구를 출력해야 한다. 단, 에러 문구는 "[ERROR]"로 시작해야 한다.
+
+### 5. 목표 (피드백)
+
+- 클래스(객체)를 분리한다.
+- 도메인 로직에 대한 단위 테스트를 작성한다.
+- 발생할 수 있는 예외 상황에 대해 고민한다.
+- 비즈니스 로직과 UI 로직을 분리한다.
+- 연관성이 있는 상수는 static final 대신 enum을 활용한다.
+- final 키워드를 사용해 값의 변경을 막는다.
+- 객체의 상태 접근을 제한한다.
+- 객체는 객체스럽게 사용한다.
+- 필드(인스턴스 변수)의 수를 줄이기 위해 노력한다.
+- 성공하는 케이스 뿐만 아니라 예외에 대한 케이스도 테스트한다.
+- 테스트 코드도 코드이므로 리팩터링을 통해 개선해 나간다.
+- 테스트를 위한 코드는 구현 코드에서 분리되어야 한다. 아래의 예시처럼 테스트를 통과하기 위해 구현 코드를 변경하거나 테스트에서만 사용되는 로직을 만들지 않는다.
+ - 테스트를 위해 접근 제어자를 바꾸는 경우
+ - 테스트 코드에서만 사용되는 메서드
+- 단위 테스트하기 어려운 코드를 단위 테스트하깅
+- private 함수를 테스트 하고 싶다면 클래스(객체) 분리를 고려한다.
+### 6. 3주 차 미션(로또 게임 🍀) 코드 리뷰를 통해 개선할 점
+
+- 지난 미션에서 개선할 필요가 있는 리뷰를 정리하여 이번 미션에서 고민하며 개선하려고 노력했습니다.
+
+<table>
+ <tr>
+ <th align="center">Type</th>
+ <th align="center">Review</th>
+ <th align="center">Reviewer</th>
+ </tr>
+ <tr><td colspan="3"></td></tr>
+ <tr>
+ <td rowspan="15"><b>✏️ 코드 리뷰</b></td>
+ <td>01. 필요한 로직에만 예외 처리를 하도록 하자.</td>
+ <td><b>@wns312</b></td>
+ </tr>
+ <tr>
+ <td>02. 클래스가 너무 많은 상수를 가지면 가독성이 떨어지기 때문에 별도의 클래스나 enum으로 분리해보자.</td>
+ <td><b>@gywns0417</b></td>
+ </tr>
+ <tr>
+ <td>03. 한 메서드가 하나의 역할을 가지도록 별도의 클래스나 메서드로 책임을 분리하자.</td>
+ <td><b>@gywns0417</b></td>
+ </tr>
+ <tr>
+ <td>04. 변경될 수 있는 정보는 상수나 enum으로 관리하고, 해당 메시지에서 값들을 참조하는 방향으로 개선하자.</td>
+ <td><b>@gywns0417</b></td>
+ </tr>
+ <tr>
+ <td>05. View가 Model에 너무 의존하게 하지 말고, 온전히 View의 역할만 하게 하도록 고려하자.</td>
+ <td><b>@twkwon0417 @youngsu5582</b></td>
+ </tr>
+ <tr>
+ <td>06. [ERROR]에 해당하는 prefix 부분은 상수로 선언하고, getMessage() 할 때 PREFIX + message 하는 식으로 사용해보자.</td>
+ <td><b>@youngsu5582</b></td>
+ </tr>
+ <tr>
+ <td>07. 변경 가능성이 있는 변수에 대해서 확장성에 대해 좀 더 고민해 보자.</td>
+ <td><b>@youngsu5582 @OiKimiO</b></td>
+ </tr>
+ <tr>
+ <td>08. 오류 발생시 해당 부분에서 다시 입력 받을 수 있도록 신경쓰자.</td>
+ <td><b>@guswlsdl0121</b></td>
+ </tr>
+ <tr>
+ <td>09. 정적 메서드를 활용하여 객체 의존성을 줄여보자.</td>
+ <td><b>@OiKimiO</b></td>
+ </tr>
+ <tr>
+ <td>10. String matches를 메서드 내부에서 사용하는 것 보다는 Pattern.matches를 static final로 관리하는 것이 성능상 이점이 있으니 활용해보자.</td>
+ <td><b>@OiKimiO</b></td>
+ </tr>
+ <tr>
+ <td>11. 포메팅을 활용하여 처리해보자.</td>
+ <td><b>@Seol-JY</b></td>
+ </tr>
+ <tr>
+ <td>12. stream을 활용하면 중복을 제거할 때 결과값을 바로 받을 수 있다.</td>
+ <td><b>@YejiGong</b></td>
+ </tr>
+ <tr>
+ <td>13. 매직 넘버를 상수로 선언하는 것은 좋으나 ZERO나 FIVE같은 직접적인 변수명 보다는 해당 값의 의미를 알려주는 변수명으로 지어보자.</td>
+ <td><b>@YejiGong</b></td>
+ </tr>
+</table>
+
+### 7. 패키지 구조
+- 아래 테이블 형식은 <b>@h-beeen</b>님의 README를 참고했습니다.
+## 📦 패키지 구조
+
+[//]: # (<img align="center" src="https://github.com/woowacourse-precourse/java-racingcar-6/assets/112257466/3ef9d8a2-d4bb-42a1-900f-754799cac3fd" height="32px"> FinalResponse</b>)
+
+<div align="center">
+<table>
+ <tr>
+ <th align="center">Package</th>
+ <th align="center">Class</th>
+ <th align="center">Description</th>
+ </tr>
+ <tr>
+ <td rowspan="4"><b><img align="center" src="https://github.com/woowacourse-precourse/java-racingcar-6/assets/112257466/2f32b4cd-187c-4b92-a136-2d86cd3341cd" width="20px"> controller</b></td>
+ <td><b><img align="center" height="32px"> EventPlannerController</b></td>
+ <td>이벤트 플래너 로직을 메인으로 동작하는 컨트롤러</td>
+ </tr>
+ <tr>
+ <td><b><img align="center" height="32px"> OrderController</b></td>
+ <td>주문을 받는 로직을 동작하는 컨트롤러</td>
+ </tr>
+ <tr>
+ <td><b><img align="center" height="32px"> ReservationController</b></td>
+ <td>방문 날짜 예약을 받는 로직을 동작하는 컨트롤러</td>
+ </tr>
+ <tr>
+ <td><b><img align="center" height="32px"> ResultController</b></td>
+ <td>방문 날짜와 주문을 토대로 결과를 출력하기 위한 로직을 동작하는 컨트롤러</td>
+ </tr>
+ <tr><td colspan="3"></td></tr>
+ <tr>
+ <td rowspan="7"><img align="center" src="https://github.com/woowacourse-precourse/java-racingcar-6/assets/112257466/f16a8719-281f-4535-a958-c1c62d69cfa2" width="20px"> <b>domain<br></b></td>
+ <td><b><img align="center" height="32px"> Calendar</b></td>
+ <td>12월 달력에 대한 정보를 갖는 enum 클래스</td>
+ </tr>
+ <tr>
+ <td><b><img align="center" height="32px"> DiscountType</b></td>
+ <td>할인 이벤트에 대한 정보를 갖는 enum 클래스</td>
+ </tr>
+ <tr>
+ <td><b><img align="center" height="32px"> EventBadge</b></td>
+ <td>이벤트 배지 부여에 대한 정보를 갖는 enum 클래스</td>
+ </tr>
+ <tr>
+ <td><b><img align="center" height="32px"> Menu</b></td>
+ <td>주문 메뉴에 대한 정보를 갖는 enum 클래스</td>
+ </tr>
+ <tr>
+ <td><b><img align="center" height="32px"> Order</b></td>
+ <td>주문에 대한 정보를 갖는 클래스</td>
+ </tr>
+ <tr>
+ <td><b><img align="center" height="32px"> Reservation</b></td>
+ <td>예약 날짜에 대한 정보를 갖는 클래스</td>
+ </tr>
+ <tr>
+ <td><b><img align="center" height="32px"> Result</b></td>
+ <td>이벤트 결과에 대한 정보를 갖는 클래스</td>
+ </tr>
+ <tr><td colspan="3"></td></tr>
+ <tr>
+ <td rowspan="2"><img align="center" src="https://github.com/woowacourse-precourse/java-racingcar-6/assets/112257466/219d6ae0-19c4-4984-970d-ea244700b6a9" width="20px"> <b>exception</b></td>
+ <td><b><img align="center" height="32px"> ErrorMessage</b></td>
+ <td>에러 메시지에 대한 정보를 갖는 enum 클래스</td>
+ </tr>
+ <tr>
+ <td><b><img align="center" height="32px"> ValidatorException</b></td>
+ <td>에러 메시지를 관리하는 클래스</td>
+ </tr>
+ <tr><td colspan="3"></td></tr>
+ <tr>
+ <td rowspan="1"><img align="center" src="https://github.com/woowacourse-precourse/java-racingcar-6/assets/112257466/219d6ae0-19c4-4984-970d-ea244700b6a9"width="20px"> <b>validator</b></td>
+ <td><b><img align="center" height="32px"> Validator</b></td>
+ <td>전반적인 검증에 대한 관리를 하는 클래스</td>
+ </tr>
+ <tr><td colspan="3"></td></tr>
+ <tr>
+ <td rowspan="3"><img align="center" src="https://github.com/woowacourse-precourse/java-racingcar-6/assets/112257466/219d6ae0-19c4-4984-970d-ea244700b6a9" width="20px"> <b>view</b></td>
+ <td><b><img align="center" height="32px"> PrintMessage</b></td>
+ <td>입출력에 관한 메시지 상수에 대한 정보를 갖는 enum 클래스</td>
+ </tr>
+ <tr>
+ <td><b><img align="center" height="32px"> InputView</b></td>
+ <td>입력을 담당하는 View 클래스</td>
+ </tr>
+ <tr>
+ <td><b><img align="center" height="32px"> OutputView</b></td>
+ <td>출력을 담당하는 View 클래스</td>
+ </tr>
+
+</table>
+</div>
+
+
\ No newline at end of file | Unknown | 게임이라고 하신 이유가 따로 있을까요? |
@@ -0,0 +1,15 @@
+package christmas.controller;
+
+import christmas.domain.Order;
+import christmas.domain.Reservation;
+import christmas.domain.Result;
+
+public class EventPlannerController {
+ public static void run() {
+ Reservation reservation = ReservationController.inputReservation();
+ Order order = OrderController.inputOrder();
+ Result result = ResultController.createResult(order, reservation);
+ ResultController.printResult(result);
+
+ }
+} | Java | static 메서드만 있는 클래스라면 인스턴스륾 만들 필요가 없을텐데요, 이를 어떻게 방지할 수 있을까요? |
@@ -0,0 +1,117 @@
+package christmas.view;
+
+import static christmas.view.messages.PrintMessage.*;
+
+import christmas.domain.Menu;
+import christmas.domain.Order;
+import christmas.domain.Result;
+import christmas.view.messages.PrintMessage;
+import java.util.Map;
+
+public class OutputView {
+ private static final int TRUE = 1;
+ private static final int FALSE = 0;
+ private static final int CHAMPAGNE = 25000;
+ public static void println(Object data) {
+ System.out.println(data);
+
+ }
+ public static void printMessage(final PrintMessage message) {
+ System.out.println(message.getMessage());
+ }
+
+ public static void printOrder(Order order) {
+ Map<Menu, Integer> orderedItems = order.getOrderedItems();
+ printMessage(OUTPUT_ORDER);
+ for (Map.Entry<Menu, Integer> entry : orderedItems.entrySet()) {
+ System.out.println(entry.getKey() + " " + entry.getValue() + COUNT.getMessage());
+ }
+ }
+
+ public static void printAllEvents(Result result) {
+ printTotalBeforeDiscount(result);
+ printServiceMenu(result);
+ printBenefit(result);
+ printWeekday(result);
+ printWeekend(result);
+ printSpecialDay(result);
+ printAllBenefit(result);
+ printTotalAfterBenefit(result);
+ printEventBadge(result);
+ }
+
+ public static void printIntroduce(int date) {
+ System.out.println(PREVIEW.getMessage(date));
+ System.out.println();
+ }
+
+ public static void printTotalBeforeDiscount(Result result) {
+ System.out.println(OUTPUT_TOTAL_BEFORE_DISCOUNT.getMessage());
+ System.out.println(result.getTotalBeforeDiscount() + "" + MONEY.getMessage());
+ System.out.println();
+ }
+
+
+ public static void printServiceMenu(Result result) {
+ System.out.println(OUTPUT_GIFT_MENU.getMessage());
+ if (result.getServiceMenu() == TRUE) {
+ System.out.println(SERVICE_MENU.getMessage());
+ }
+ if (result.getServiceMenu() == FALSE) {
+ System.out.println(NONE.getMessage());
+ }
+ System.out.println();
+ }
+
+ public static void printBenefit(Result result) {
+ System.out.println(OUTPUT_BENEFIT.getMessage());
+ if (result.getdDayDiscount() == FALSE) {
+ System.out.println(NONE.getMessage());
+ }
+ if (result.getdDayDiscount() != FALSE) {
+ System.out.println(CHRISTMAS_DISCOUNT.getMessage() + result.getdDayDiscount() + "" + MONEY.getMessage());
+ }
+ }
+
+ public static void printWeekday(Result result) {
+ if (result.getWeekdayDiscount() != FALSE) {
+ System.out.println(WEEKDAY_DISCOUNT.getMessage() + result.getWeekdayDiscount() + MONEY.getMessage());
+ }
+ }
+
+ public static void printWeekend(Result result) {
+ if (result.getWeekendDiscount() != FALSE) {
+ System.out.println(WEEKEND_DISCOUNT.getMessage() + result.getWeekendDiscount() + MONEY.getMessage());
+ }
+ }
+
+ public static void printSpecialDay(Result result) {
+ if (result.getServiceMenu() == TRUE) {
+ System.out.println(SPECIAL_DISCOUNT.getMessage() + result.getSpecialDiscount() + MONEY.getMessage());
+ System.out.println(SERVICE_DISCOUNT.getMessage() + CHAMPAGNE + MONEY.getMessage());
+ }
+ System.out.println();
+ }
+
+ public static void printAllBenefit(Result result) {
+ System.out.println(BENEFIT_ALL_DISCOUNT.getMessage());
+ if (result.getTotalBenefit() != FALSE) {
+ System.out.println("-" + result.getTotalBenefit() + MONEY.getMessage());
+ }
+ if (result.getTotalBenefit() == FALSE) {
+ System.out.println(result.getTotalBenefit() + MONEY.getMessage());
+ }
+ System.out.println();
+ }
+
+ public static void printTotalAfterBenefit(Result result) {
+ System.out.println(AFTER_BENEFIT_DISCOUNT.getMessage());
+ System.out.println(result.getTotalAfterBenefit() + MONEY.getMessage());
+ System.out.println();
+ }
+
+ public static void printEventBadge(Result result) {
+ System.out.println(BADGE_DISCOUNT.getMessage());
+ System.out.println(result.getBadge());
+ }
+} | Java | 불필요한 개행은 지워주세요..! |
@@ -3,7 +3,10 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>React App</title>
+ <meta name="description" content="Web site created using create-react-app"/>
+ <link href="https://fonts.googleapis.com/css2?family=Lobster&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
+ <title>Westagram</title>
</head>
<body>
<div id="root"></div> | Unknown | description은 없어도 되지 않을까요? 잘 모르겠습니다 ㅎㅎ |
@@ -0,0 +1,50 @@
+import React from 'react';
+import { withRouter } from 'react-router-dom';
+import './Login.scss';
+
+
+class LoginJaeyoung extends React.Component {
+ constructor () {
+ super();
+ this.state = {
+ id: '',
+ pw : '',
+ };
+ }
+
+ handleInput = (e) => {
+ const { name,value} = e.target;
+ this.setState({
+ [name]: value
+ })
+ }
+
+ goToMain = () => {
+ this.props.history.push('/main-jaeyoung')
+ }
+
+
+ render () {
+ const { handleInput } = this
+ const isBtnAble = this.state.id.includes('@') && this.state.pw.length >= 5;
+
+
+ return (
+ <div className="loginContainer">
+ <div className="logoName">
+ <h1>Instargram</h1>
+ </div>
+ <div className="loginInfo">
+ <input type="text" name="id" onChange={handleInput} className="loginId" placeholder="전화번호, 사용자 이름 또는 이메일" />
+ <input type="password" name="pw" onChange={handleInput} className="loginPs" placeholder="비밀번호"/>
+ <button className="loginBt" onClick={this.goToMain} disabled={!isBtnAble}>로그인</button>
+ </div>
+ <div className="forgetPassword">
+ <a href="https://www.naver.com/">비밀번호를 잊으셨나요?</a>
+ </div>
+ </div>
+ )
+ }
+}
+
+export default withRouter( LoginJaeyoung );
\ No newline at end of file | JavaScript | https://www.notion.so/wecode/React-Refactoring-Check-List-aea297cf88ed4601b769e4b2c2cfd4e1#089493d6bfca438aa328226e327cff92
이 부분을 참고하면 하나의 메소드롤 묶을 수 있습니다. |
@@ -0,0 +1,85 @@
+* {
+ box-sizing: border-box;
+}
+
+.loginContainer {
+ border: 2px solid #e6e6e6;
+ width: 350px;
+ height: 380px;
+ margin: 0 auto;
+ .logoName {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 100%;
+ h1 {
+ font-family: "Lobster", cursive;
+ width: 175px;
+ height: 52px;
+ text-align: center;
+ padding-top: 6px;
+ }
+ }
+ .loginInfo {
+ height: 213px;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ padding-top: 10px;
+ .loginId {
+ width: 268px;
+ height: 38px;
+ margin-bottom: 5px;
+ padding-left: 10px;
+ border-radius: 3px;
+ border: 1px solid #efefef;
+ background: #fafafa;
+ color: #9c9c9c;
+ font-size: 14px;
+ &:focus {
+ outline-color: gray;
+ }
+ }
+ .loginPs {
+ width: 268px;
+ height: 38px;
+ margin-bottom: 5px;
+ padding-left: 10px;
+ border-radius: 3px;
+ border: 1px solid #efefef;
+ background: #fafafa;
+ color: #9c9c9c;
+ font-size: 14px;
+ &:focus {
+ outline-color: gray;
+ }
+ }
+ .loginBt {
+ width: 268px;
+ height: 30px;
+ margin-top: 5px;
+ border-radius: 3px;
+ background-color: #2795f6;
+ color: #ffffff;
+ border-style: none;
+
+ &:focus {
+ outline: none;
+ }
+
+ &:disabled {
+ background-color: #b2dffc;
+ }
+ }
+ }
+ .forgetPassword{
+ display: flex;
+ justify-content: center;
+ margin-top: 20px;
+ a {
+ color: #043569; text-decoration: none;
+ }
+ }
+
+
+} | Unknown | 이 부분은 common.css에 있으면 좋을 것 같습니다. |
@@ -0,0 +1,85 @@
+* {
+ box-sizing: border-box;
+}
+
+.loginContainer {
+ border: 2px solid #e6e6e6;
+ width: 350px;
+ height: 380px;
+ margin: 0 auto;
+ .logoName {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 100%;
+ h1 {
+ font-family: "Lobster", cursive;
+ width: 175px;
+ height: 52px;
+ text-align: center;
+ padding-top: 6px;
+ }
+ }
+ .loginInfo {
+ height: 213px;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ padding-top: 10px;
+ .loginId {
+ width: 268px;
+ height: 38px;
+ margin-bottom: 5px;
+ padding-left: 10px;
+ border-radius: 3px;
+ border: 1px solid #efefef;
+ background: #fafafa;
+ color: #9c9c9c;
+ font-size: 14px;
+ &:focus {
+ outline-color: gray;
+ }
+ }
+ .loginPs {
+ width: 268px;
+ height: 38px;
+ margin-bottom: 5px;
+ padding-left: 10px;
+ border-radius: 3px;
+ border: 1px solid #efefef;
+ background: #fafafa;
+ color: #9c9c9c;
+ font-size: 14px;
+ &:focus {
+ outline-color: gray;
+ }
+ }
+ .loginBt {
+ width: 268px;
+ height: 30px;
+ margin-top: 5px;
+ border-radius: 3px;
+ background-color: #2795f6;
+ color: #ffffff;
+ border-style: none;
+
+ &:focus {
+ outline: none;
+ }
+
+ &:disabled {
+ background-color: #b2dffc;
+ }
+ }
+ }
+ .forgetPassword{
+ display: flex;
+ justify-content: center;
+ margin-top: 20px;
+ a {
+ color: #043569; text-decoration: none;
+ }
+ }
+
+
+} | Unknown | font-family같은 속성은 width나 margin아래에 있으면 좋을 것 같습니다. |
@@ -0,0 +1,190 @@
+import React from 'react';
+import FeedComponent from './FeedComponent/FeedComponent';
+import './Main.scss';
+import explore from '../../../images/jaeyoungLee/Main/explore.jpg';
+import heart from '../../../images/jaeyoungLee/Main/heart.jpg';
+import profile from '../../../images/jaeyoungLee/Main/profile.jpg';
+import heungminSon from '../../../images/jaeyoungLee/Main/손흥민.jpg';
+class MainJaeyoung extends React.Component {
+ constructor () {
+ super();
+ this.state = {
+ commentFeed : [],
+ }
+ }
+
+ componentDidMount() {
+ fetch('http://localhost:3000/data/feedData.json', {
+ method: 'GET'
+ })
+ .then(res => res.json())
+ .then(data => {
+ this.setState({
+ commentFeed: data,
+ });
+ });
+ }
+
+
+
+ render(){
+ const { commentFeed } = this.state;
+ return(
+ <>
+ <nav>
+ <div className="navcontents">
+ <div className="navleft">
+ <div className="navleftcontents">
+ <span className="logo"><i className="fab fa-instagram"></i></span>
+ <h1 className="logoname">westagram</h1>
+ </div>
+ </div>
+ <div className="navcenter">
+ <div className="navcentercontents">
+ <input className="search" type="text" placeholder="검색"/>
+ <span className="searchimg"><i className="fas fa-search"></i></span>
+ </div>
+ </div>
+ <div className="navright">
+ <div className="navrightcontents">
+ <img className="navexplore" src={explore} alt="탐험"/>
+ <img className="navheart" src={heart} alt="하트"/>
+ <img className="navprofile" src={profile} alt="프로필"/>
+ </div>
+ </div>
+ </div>
+ </nav>
+ <div className="main">
+ <div className="feeds">
+ <div className="story">
+ <div className="storyimgbox">
+ <div className="storycontents">
+ <div className="storyprofile">
+ <div className="storylastbox">
+ <div className="storylast">
+ <img className="storyimg1" src={heungminSon} alt="프로필1"/>
+ <p className="storyp1">손흥민</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://instagram.famm6-1.fna.fbcdn.net/v/t51.2885-19/44884218_345707102882519_2446069589734326272_n.jpg?_nc_ht=instagram.famm6-1.fna.fbcdn.net&_nc_ohc=mhDR9_0DpXIAX_KX0iq&ccb=7-4&oh=dcbb150241d6b1336dd54a4a20417b2a&oe=608B680F&_nc_sid=712cc3&ig_cache_key=YW5vbnltb3VzX3Byb2ZpbGVfcGlj.2-ccb7-4" alt="프로필1"/>
+ <p className="storyp1">2wo0</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/35999304_258159611658935_7092278198804676608_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=et4sZhNbgpAAX-qKBH9&ccb=7-4&oh=0b254f6fb3e4182513c3e20ed1a326d0&oe=608BC5C1&_nc_sid=48a2a6" alt="프로필1"/>
+ <p className="storyp1">geg</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/150675895_144233967522798_7515094658452540248_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=xslO4Za0644AX9cwObZ&ccb=7-4&oh=0f5cb82fd80b51b47d74e160e228aa1c&oe=608D7B5E&_nc_sid=48a2a6" alt="프로필1"/>
+ <p className="storyp1">h._.j</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/135771971_1881013862054625_6713353513169410837_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=SxJIiqRh4rcAX8RSLYk&ccb=7-4&oh=6dec08c37a69cb2c2a14f21bc36b5eef&oe=608C0912&_nc_sid=48a2a6" alt="프로필1"/>
+ <p className="storyp1">idon</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/155951500_335125831259326_3729086392261698560_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=3nnTQdlVU98AX_4fVMv&ccb=7-4&oh=4a596fc0e33f2ece37634ae50d38cdde&oe=608C5901&_nc_sid=48a2a6" alt="프로필1"/>
+ <p className="storyp1">dfewg</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/37828240_293117218102022_6759937585105076224_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=jzs6QvrGtHAAX_qFR80&ccb=7-4&oh=f4984cbce61bc445f02622a5468278b3&oe=608B09A1&_nc_sid=57d425" alt="프로필1"/>
+ <p className="storyp1">33gg</p>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ {commentFeed.map((feed,id) =>{
+ return (
+ <FeedComponent key={feed.id} profileimg={feed.profileimg} userName={feed.userName} feedimg={feed.feedimg} feedcontent={feed.feedcontent} />
+ );
+ })}
+
+ </div>
+ <div className="main-right">
+ <div className="my_profile">
+ <img className="my_profileimg" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/141997127_1523884024669097_6148385093252095280_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=ldPmBqcpW3kAX9esSCC&ccb=7-4&oh=6503a99b1b0096ad362012fef7e72aed&oe=6085537E&_nc_sid=7b02f1" alt="프로필"/>
+ <div className="my_info">
+ <p className="mynickname">2wo0_0</p>
+ <p className="myname">이재영</p>
+ </div>
+ <button className="profile_transform" disabled>전환</button>
+ </div>
+ <div className="recommendation">
+ <div className="recommendation_header">
+ <p className="recommendation_left">회원님을 위한 추천</p>
+ <p className="recommendation_right">모두 보기</p>
+ </div>
+ <div className="recommendation_info">
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/156650140_116853317083347_8770042214751161261_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=-evbCZABANYAX_WcDzP&edm=AEF8tYYAAAAA&ccb=7-4&oh=5eb6e52a64b2ad8c98bff45dab473831&oe=60880D5B&_nc_sid=a9513d" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">ryu_d_g</p>
+ <p className="other_friend">1996yunsi님 외 13명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/159992110_105322351555148_1839915921172216453_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=xfLIvYCwwiIAX8AJI08&ccb=7-4&oh=7bdaf0e022e88f0dd5079c1995892031&oe=608D9B9E&_nc_sid=57d425" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">2s2_f</p>
+ <p className="other_friend">_sihyeon___님 외 49명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/160716680_272942871038831_8108440433038115559_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=VmeF5WmeLg4AX-jiUAL&ccb=7-4&oh=cf29d0253e8afb755a9d26ad13a6deda&oe=608D4A0C&_nc_sid=a9513d" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">rdfe_g</p>
+ <p className="other_friend">111_fkdn님 외 5명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/164274433_776408706413539_3215024154205561736_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=gCCfowKp9OMAX9_NBIP&ccb=7-4&oh=afbada353869184275b4d3be70f38605&oe=608BE909&_nc_sid=a9513d" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">cat_2d_g</p>
+ <p className="other_friend">cjdtkseh님 외 15명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src=" https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/164520013_834814623778500_398528442563386719_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=iLm66uEJKQ4AX88GkVl&ccb=7-4&oh=4fe271ebb6f627b328cb3d24bb811776&oe=608E6098&_nc_sid=86f79a" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">tksdkdnENr</p>
+ <p className="other_friend">cjfcjfgme1님 외 32명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ </div>
+ </div>
+ <aside>
+ <ul className="westagram_contents_box">
+ {CONTENTS.map((el,id) =>
+ <li key={id} className="westagram_contents">{el.content}</li>
+ )}
+
+ </ul>
+ <p className="westagram_facebook">© 2021 INSTAGRAM FROM FACEBOOK</p>
+ </aside>
+ </div>
+ </div>
+ </>
+ )
+ }
+}
+export default MainJaeyoung ;
+
+const CONTENTS = [
+ {id: 1, content: "소개"},
+ {id: 2, content: "도움말"},
+ {id: 3, content: "홍보 센터"},
+ {id: 4, content: "API"},
+ {id: 5, content: "채용정보"},
+ {id: 6, content: "개인정보처리방침"},
+ {id: 7, content: "약관"},
+ {id: 8, content: "위치"},
+ {id: 9, content: "인기 계정"},
+ {id: 10, content: "해시태그"},
+ {id: 11, content: "언어"},
+]
\ No newline at end of file | JavaScript | 변수명이 명식적이여서 좋은 것 같습니다.! |
@@ -0,0 +1,190 @@
+import React from 'react';
+import FeedComponent from './FeedComponent/FeedComponent';
+import './Main.scss';
+import explore from '../../../images/jaeyoungLee/Main/explore.jpg';
+import heart from '../../../images/jaeyoungLee/Main/heart.jpg';
+import profile from '../../../images/jaeyoungLee/Main/profile.jpg';
+import heungminSon from '../../../images/jaeyoungLee/Main/손흥민.jpg';
+class MainJaeyoung extends React.Component {
+ constructor () {
+ super();
+ this.state = {
+ commentFeed : [],
+ }
+ }
+
+ componentDidMount() {
+ fetch('http://localhost:3000/data/feedData.json', {
+ method: 'GET'
+ })
+ .then(res => res.json())
+ .then(data => {
+ this.setState({
+ commentFeed: data,
+ });
+ });
+ }
+
+
+
+ render(){
+ const { commentFeed } = this.state;
+ return(
+ <>
+ <nav>
+ <div className="navcontents">
+ <div className="navleft">
+ <div className="navleftcontents">
+ <span className="logo"><i className="fab fa-instagram"></i></span>
+ <h1 className="logoname">westagram</h1>
+ </div>
+ </div>
+ <div className="navcenter">
+ <div className="navcentercontents">
+ <input className="search" type="text" placeholder="검색"/>
+ <span className="searchimg"><i className="fas fa-search"></i></span>
+ </div>
+ </div>
+ <div className="navright">
+ <div className="navrightcontents">
+ <img className="navexplore" src={explore} alt="탐험"/>
+ <img className="navheart" src={heart} alt="하트"/>
+ <img className="navprofile" src={profile} alt="프로필"/>
+ </div>
+ </div>
+ </div>
+ </nav>
+ <div className="main">
+ <div className="feeds">
+ <div className="story">
+ <div className="storyimgbox">
+ <div className="storycontents">
+ <div className="storyprofile">
+ <div className="storylastbox">
+ <div className="storylast">
+ <img className="storyimg1" src={heungminSon} alt="프로필1"/>
+ <p className="storyp1">손흥민</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://instagram.famm6-1.fna.fbcdn.net/v/t51.2885-19/44884218_345707102882519_2446069589734326272_n.jpg?_nc_ht=instagram.famm6-1.fna.fbcdn.net&_nc_ohc=mhDR9_0DpXIAX_KX0iq&ccb=7-4&oh=dcbb150241d6b1336dd54a4a20417b2a&oe=608B680F&_nc_sid=712cc3&ig_cache_key=YW5vbnltb3VzX3Byb2ZpbGVfcGlj.2-ccb7-4" alt="프로필1"/>
+ <p className="storyp1">2wo0</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/35999304_258159611658935_7092278198804676608_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=et4sZhNbgpAAX-qKBH9&ccb=7-4&oh=0b254f6fb3e4182513c3e20ed1a326d0&oe=608BC5C1&_nc_sid=48a2a6" alt="프로필1"/>
+ <p className="storyp1">geg</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/150675895_144233967522798_7515094658452540248_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=xslO4Za0644AX9cwObZ&ccb=7-4&oh=0f5cb82fd80b51b47d74e160e228aa1c&oe=608D7B5E&_nc_sid=48a2a6" alt="프로필1"/>
+ <p className="storyp1">h._.j</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/135771971_1881013862054625_6713353513169410837_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=SxJIiqRh4rcAX8RSLYk&ccb=7-4&oh=6dec08c37a69cb2c2a14f21bc36b5eef&oe=608C0912&_nc_sid=48a2a6" alt="프로필1"/>
+ <p className="storyp1">idon</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/155951500_335125831259326_3729086392261698560_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=3nnTQdlVU98AX_4fVMv&ccb=7-4&oh=4a596fc0e33f2ece37634ae50d38cdde&oe=608C5901&_nc_sid=48a2a6" alt="프로필1"/>
+ <p className="storyp1">dfewg</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/37828240_293117218102022_6759937585105076224_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=jzs6QvrGtHAAX_qFR80&ccb=7-4&oh=f4984cbce61bc445f02622a5468278b3&oe=608B09A1&_nc_sid=57d425" alt="프로필1"/>
+ <p className="storyp1">33gg</p>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ {commentFeed.map((feed,id) =>{
+ return (
+ <FeedComponent key={feed.id} profileimg={feed.profileimg} userName={feed.userName} feedimg={feed.feedimg} feedcontent={feed.feedcontent} />
+ );
+ })}
+
+ </div>
+ <div className="main-right">
+ <div className="my_profile">
+ <img className="my_profileimg" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/141997127_1523884024669097_6148385093252095280_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=ldPmBqcpW3kAX9esSCC&ccb=7-4&oh=6503a99b1b0096ad362012fef7e72aed&oe=6085537E&_nc_sid=7b02f1" alt="프로필"/>
+ <div className="my_info">
+ <p className="mynickname">2wo0_0</p>
+ <p className="myname">이재영</p>
+ </div>
+ <button className="profile_transform" disabled>전환</button>
+ </div>
+ <div className="recommendation">
+ <div className="recommendation_header">
+ <p className="recommendation_left">회원님을 위한 추천</p>
+ <p className="recommendation_right">모두 보기</p>
+ </div>
+ <div className="recommendation_info">
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/156650140_116853317083347_8770042214751161261_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=-evbCZABANYAX_WcDzP&edm=AEF8tYYAAAAA&ccb=7-4&oh=5eb6e52a64b2ad8c98bff45dab473831&oe=60880D5B&_nc_sid=a9513d" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">ryu_d_g</p>
+ <p className="other_friend">1996yunsi님 외 13명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/159992110_105322351555148_1839915921172216453_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=xfLIvYCwwiIAX8AJI08&ccb=7-4&oh=7bdaf0e022e88f0dd5079c1995892031&oe=608D9B9E&_nc_sid=57d425" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">2s2_f</p>
+ <p className="other_friend">_sihyeon___님 외 49명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/160716680_272942871038831_8108440433038115559_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=VmeF5WmeLg4AX-jiUAL&ccb=7-4&oh=cf29d0253e8afb755a9d26ad13a6deda&oe=608D4A0C&_nc_sid=a9513d" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">rdfe_g</p>
+ <p className="other_friend">111_fkdn님 외 5명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/164274433_776408706413539_3215024154205561736_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=gCCfowKp9OMAX9_NBIP&ccb=7-4&oh=afbada353869184275b4d3be70f38605&oe=608BE909&_nc_sid=a9513d" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">cat_2d_g</p>
+ <p className="other_friend">cjdtkseh님 외 15명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src=" https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/164520013_834814623778500_398528442563386719_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=iLm66uEJKQ4AX88GkVl&ccb=7-4&oh=4fe271ebb6f627b328cb3d24bb811776&oe=608E6098&_nc_sid=86f79a" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">tksdkdnENr</p>
+ <p className="other_friend">cjfcjfgme1님 외 32명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ </div>
+ </div>
+ <aside>
+ <ul className="westagram_contents_box">
+ {CONTENTS.map((el,id) =>
+ <li key={id} className="westagram_contents">{el.content}</li>
+ )}
+
+ </ul>
+ <p className="westagram_facebook">© 2021 INSTAGRAM FROM FACEBOOK</p>
+ </aside>
+ </div>
+ </div>
+ </>
+ )
+ }
+}
+export default MainJaeyoung ;
+
+const CONTENTS = [
+ {id: 1, content: "소개"},
+ {id: 2, content: "도움말"},
+ {id: 3, content: "홍보 센터"},
+ {id: 4, content: "API"},
+ {id: 5, content: "채용정보"},
+ {id: 6, content: "개인정보처리방침"},
+ {id: 7, content: "약관"},
+ {id: 8, content: "위치"},
+ {id: 9, content: "인기 계정"},
+ {id: 10, content: "해시태그"},
+ {id: 11, content: "언어"},
+]
\ No newline at end of file | JavaScript | ```suggestion
inputKeyPress= (e) => {
```
같은 이름은 어떨까요? 메소드가 많아지면 헷갈릴 수 있을 거 같습니다. |
@@ -0,0 +1,412 @@
+* {
+ margin: 0;
+ padding: 0;
+}
+nav {
+ position: fixed;
+ width: 100%;
+ top: 0px;
+ left: 0px;
+ right: 0px;
+ background-color: #fff;
+ border-bottom: 1px solid #dbdbdb;
+ .navcontents {
+ width: 935px;
+ height: 54px;
+ background-color: #fff;
+ margin: 0 auto;
+ display: flex;
+ justify-content: space-between;
+ .navleft {
+ width: 360px;
+ .navleftcontents {
+ display: flex;
+ justify-content: flex-start;
+ .logo {
+ font-size: 23px;
+ margin-top: 12px;
+ }
+ .logoname {
+ border-left: 1px solid #bbbbbb;
+ font-family: "Lobster", cursive;
+ margin-left: 15px;
+ margin-top: 7px;
+ padding-left: 15px;
+ }
+ }
+ }
+ .navcenter {
+ width: 215px;
+ .navcentercontents {
+ position: relative;
+ .search {
+ width: 213px;
+ height: 26px;
+ background-color: #fafafa;
+ border: 1px solid #dbdbdb;
+ border-radius: 3px;
+ text-align: center;
+ position: absolute;
+ top: 14px;
+ }
+
+ .searchimg {
+ font-size: 10px;
+ color: #bbbbbb;
+ position: absolute;
+ top: 24px;
+ left: 83px;
+ }
+ }
+ }
+ .navright {
+ width: 360px;
+ .navrightcontents {
+ display: flex;
+ justify-content: flex-end;
+ margin-top: 14px;
+ .navexplore {
+ width: 25px;
+ height: 25px;
+ margin-right: 20px;
+ }
+
+ .navheart {
+ width: 25px;
+ height: 25px;
+ margin-right: 20px;
+ }
+
+ .navprofile {
+ width: 25px;
+ height: 25px;
+ }
+ }
+ }
+ }
+}
+
+
+
+.main {
+ border: 1px solid #fafafa;
+ background-color: #fafafa;
+ .feeds {
+ width: 935px;
+ margin: 0 auto;
+ margin-top: 84px;
+ .story {
+ width: 612px;
+ height: 116px;
+ background-color: #fff;
+ border: 1px solid #dbdbdb;
+ border-radius: 3px;
+ display: flex;
+ align-items: center;
+ .storyimgbox {
+ width: 612px;
+ height: 84px;
+ .storycontents {
+ display: flex;
+ justify-content: space-around;
+ .storylastbox {
+ display: flex;
+ justify-content: center;
+ .storylast {
+ width: 80px;
+ height: 122px;
+ .storyimg1 {
+ width: 56px;
+ height: 56px;
+ border: 1px solid #ececec;
+ border-radius: 50%;
+ padding: 3px;
+ object-fit: cover;
+ }
+
+ .storyp1 {
+ color: #8e8e8e;
+ font-size: 12px;
+ margin-left: 18px;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+
+article {
+ width: 612px;
+ height: auto;
+ background-color: #fff;
+ margin-top: 24px;
+ border: 1px solid #dbdbdb;
+ border-radius: 3px;
+ .articleheader {
+ width: 612px;
+ height: 59px;
+ border: 1px solid #dbdbdb;
+ .articleheadercontents {
+ width: 582px;
+ height: 27px;
+ margin: 15px auto 15px auto;
+ display: flex;
+ justify-content: space-between;
+ .headerimg {
+ width: 32px;
+ height: 32px;
+ border-radius: 50%;
+ object-fit: cover;
+ }
+
+ .headername {
+ width: 536px;
+ height: 26px;
+ .headerlast {
+ height: 26px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ .hname {
+ font-size: 14px;
+ color: #262626;
+ font-weight: bold;
+ }
+ }
+ }
+ }
+ }
+ .articleimg {
+ width: 612px;
+ height: 612px;
+ object-fit: cover;
+ }
+
+ .article_button {
+ width: 582px;
+ height: 49px;
+ margin: 0 auto;
+ display: flex;
+ justify-content: space-between;
+ .article_button_left{
+ .left_button {
+ margin: 8px;
+ }
+ }
+ .article_button_right {
+ .right_button {
+ margin: 8px;
+ }
+ }
+ }
+
+ .number_of_likes {
+ width: 582px;
+ height: 18px;
+ margin: 0 auto;
+ padding-left: 5px;
+ .likes_friend {
+ font-size: 14px;
+ .like_font {
+ color: #262626;
+ font-weight: bold;
+ }
+ }
+ }
+ .friend_comment {
+ width: 582px;
+ height: auto;
+ margin: 0 auto;
+ margin-top: 8px;
+ padding-left: 5px;
+ .explanation {
+ font-size: 14px;
+ .like_font {
+ color: #262626;
+ font-weight: bold;
+ }
+ }
+ .commentBox {
+ list-style: none;
+ }
+ }
+ .time {
+ width: 598px;
+ padding-left: 18px;
+ .a_few_hours_ago {
+ font-size: 10px;
+ color: #8e8e8e;
+ }
+ }
+ .leave_comment_box {
+ border-top: 1px solid #dbdbdb;
+ margin-top: 10px;
+ .leave_comment {
+ width: 582px;
+ height: 55px;
+ margin: 0 auto;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ .smilebox {
+ padding: 8px 15px 8px 0px;
+ }
+ .inputcomment {
+ width: 510px;
+ border: 0;
+ }
+ .inputcomment:focus {
+ outline: none;
+ }
+ .posting_button {
+ background-color: #fff;
+ color: #0095f6;
+ border: 0;
+ }
+ .posting_button:focus{
+ outline: none;
+ }
+ }
+ }
+}
+
+
+
+
+.main-right {
+ width: 293px;
+ height: 612px;
+ position: fixed;
+ top: 85px;
+ left: 885px;
+ .my_profile {
+ width: 293px;
+ height: 56px;
+ margin: 18px 0px 10px 0px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ .my_profileimg {
+ width: 56px;
+ height: 56px;
+ border-radius: 50%;
+ }
+
+ .my_info {
+ width: 202px;
+ height: 30px;
+ .mynickname {
+ width: 190px;
+ font-size: 14px;
+ font-weight: bold;
+ margin-left: 12px;
+ color: #262626;
+ }
+
+ .myname {
+ width: 190px;
+ font-size: 14px;
+ margin-left: 12px;
+ color: #8e8e8e;
+ }
+ }
+ .profile_transform {
+ font-weight: 600;
+ font-size: 12px;
+ border: 0;
+ color: #0095f6;
+ }
+ }
+ .recommendation {
+ width: 291px;
+ height: 325px;
+ .recommendation_header {
+ width: 293px;
+ height: 11px;
+ margin-top: 18px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ .recommendation_left {
+ width: 248px;
+ font-size: 14px;
+ color: #8e8e8e;
+ font-weight: 600;
+ }
+
+ .recommendation_right {
+ width: 45px;
+ font-size: 12px;
+ color: #262626;
+ font-weight: 600;
+ }
+ }
+ .recommendation_info {
+ width: 289px;
+ height: 240px;
+ margin-top: 20px;
+ .recommendation_box {
+ width: 289px;
+ margin-bottom: 16px;
+ display: flex;
+ justify-content: space-between;
+ flex-wrap: wrap;
+ align-content: flex-start;
+ .friend_profile {
+ width: 32px;
+ height: 32px;
+ border-radius: 50%;
+ }
+
+ .friend_info {
+ width: 206px;
+ height: 28px;
+ .friend_nickname {
+ width: 205px;
+ color: #262626;
+ font-weight: bold;
+ font-size: 14px;
+ }
+
+ .other_friend {
+ width: 205px;
+ color: #8e8e8e;
+ font-weight: 400;
+ font-size: 12px;
+ }
+ }
+ .follow {
+ height: 15px;
+ font-weight: 600;
+ font-size: 12px;
+ margin-top: 10px;
+ border: 0;
+ color: #0095f6;
+ }
+ }
+ }
+ }
+ aside {
+ width: 293px;
+ height: 68px;
+ .westagram_contents_box {
+ width: 293px;
+ .westagram_contents {
+ color: #c7c7c7;
+ font-size: 11px;
+ font-weight: 400;
+ display: inline;
+ }
+ }
+ .westagram_facebook {
+ width: 205px;
+ color: #c7c7c7;
+ font-size: 11px;
+ font-weight: 400;
+ margin-top: 20px;
+ }
+ }
+}
\ No newline at end of file | Unknown | ```suggestion
.nav_center {
```
같이 띄어쓰기를 '-'나 '_'로 표시해주면 속성읽기가 더 수월해 질 거 같습니다! |
@@ -0,0 +1,412 @@
+* {
+ margin: 0;
+ padding: 0;
+}
+nav {
+ position: fixed;
+ width: 100%;
+ top: 0px;
+ left: 0px;
+ right: 0px;
+ background-color: #fff;
+ border-bottom: 1px solid #dbdbdb;
+ .navcontents {
+ width: 935px;
+ height: 54px;
+ background-color: #fff;
+ margin: 0 auto;
+ display: flex;
+ justify-content: space-between;
+ .navleft {
+ width: 360px;
+ .navleftcontents {
+ display: flex;
+ justify-content: flex-start;
+ .logo {
+ font-size: 23px;
+ margin-top: 12px;
+ }
+ .logoname {
+ border-left: 1px solid #bbbbbb;
+ font-family: "Lobster", cursive;
+ margin-left: 15px;
+ margin-top: 7px;
+ padding-left: 15px;
+ }
+ }
+ }
+ .navcenter {
+ width: 215px;
+ .navcentercontents {
+ position: relative;
+ .search {
+ width: 213px;
+ height: 26px;
+ background-color: #fafafa;
+ border: 1px solid #dbdbdb;
+ border-radius: 3px;
+ text-align: center;
+ position: absolute;
+ top: 14px;
+ }
+
+ .searchimg {
+ font-size: 10px;
+ color: #bbbbbb;
+ position: absolute;
+ top: 24px;
+ left: 83px;
+ }
+ }
+ }
+ .navright {
+ width: 360px;
+ .navrightcontents {
+ display: flex;
+ justify-content: flex-end;
+ margin-top: 14px;
+ .navexplore {
+ width: 25px;
+ height: 25px;
+ margin-right: 20px;
+ }
+
+ .navheart {
+ width: 25px;
+ height: 25px;
+ margin-right: 20px;
+ }
+
+ .navprofile {
+ width: 25px;
+ height: 25px;
+ }
+ }
+ }
+ }
+}
+
+
+
+.main {
+ border: 1px solid #fafafa;
+ background-color: #fafafa;
+ .feeds {
+ width: 935px;
+ margin: 0 auto;
+ margin-top: 84px;
+ .story {
+ width: 612px;
+ height: 116px;
+ background-color: #fff;
+ border: 1px solid #dbdbdb;
+ border-radius: 3px;
+ display: flex;
+ align-items: center;
+ .storyimgbox {
+ width: 612px;
+ height: 84px;
+ .storycontents {
+ display: flex;
+ justify-content: space-around;
+ .storylastbox {
+ display: flex;
+ justify-content: center;
+ .storylast {
+ width: 80px;
+ height: 122px;
+ .storyimg1 {
+ width: 56px;
+ height: 56px;
+ border: 1px solid #ececec;
+ border-radius: 50%;
+ padding: 3px;
+ object-fit: cover;
+ }
+
+ .storyp1 {
+ color: #8e8e8e;
+ font-size: 12px;
+ margin-left: 18px;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+
+article {
+ width: 612px;
+ height: auto;
+ background-color: #fff;
+ margin-top: 24px;
+ border: 1px solid #dbdbdb;
+ border-radius: 3px;
+ .articleheader {
+ width: 612px;
+ height: 59px;
+ border: 1px solid #dbdbdb;
+ .articleheadercontents {
+ width: 582px;
+ height: 27px;
+ margin: 15px auto 15px auto;
+ display: flex;
+ justify-content: space-between;
+ .headerimg {
+ width: 32px;
+ height: 32px;
+ border-radius: 50%;
+ object-fit: cover;
+ }
+
+ .headername {
+ width: 536px;
+ height: 26px;
+ .headerlast {
+ height: 26px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ .hname {
+ font-size: 14px;
+ color: #262626;
+ font-weight: bold;
+ }
+ }
+ }
+ }
+ }
+ .articleimg {
+ width: 612px;
+ height: 612px;
+ object-fit: cover;
+ }
+
+ .article_button {
+ width: 582px;
+ height: 49px;
+ margin: 0 auto;
+ display: flex;
+ justify-content: space-between;
+ .article_button_left{
+ .left_button {
+ margin: 8px;
+ }
+ }
+ .article_button_right {
+ .right_button {
+ margin: 8px;
+ }
+ }
+ }
+
+ .number_of_likes {
+ width: 582px;
+ height: 18px;
+ margin: 0 auto;
+ padding-left: 5px;
+ .likes_friend {
+ font-size: 14px;
+ .like_font {
+ color: #262626;
+ font-weight: bold;
+ }
+ }
+ }
+ .friend_comment {
+ width: 582px;
+ height: auto;
+ margin: 0 auto;
+ margin-top: 8px;
+ padding-left: 5px;
+ .explanation {
+ font-size: 14px;
+ .like_font {
+ color: #262626;
+ font-weight: bold;
+ }
+ }
+ .commentBox {
+ list-style: none;
+ }
+ }
+ .time {
+ width: 598px;
+ padding-left: 18px;
+ .a_few_hours_ago {
+ font-size: 10px;
+ color: #8e8e8e;
+ }
+ }
+ .leave_comment_box {
+ border-top: 1px solid #dbdbdb;
+ margin-top: 10px;
+ .leave_comment {
+ width: 582px;
+ height: 55px;
+ margin: 0 auto;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ .smilebox {
+ padding: 8px 15px 8px 0px;
+ }
+ .inputcomment {
+ width: 510px;
+ border: 0;
+ }
+ .inputcomment:focus {
+ outline: none;
+ }
+ .posting_button {
+ background-color: #fff;
+ color: #0095f6;
+ border: 0;
+ }
+ .posting_button:focus{
+ outline: none;
+ }
+ }
+ }
+}
+
+
+
+
+.main-right {
+ width: 293px;
+ height: 612px;
+ position: fixed;
+ top: 85px;
+ left: 885px;
+ .my_profile {
+ width: 293px;
+ height: 56px;
+ margin: 18px 0px 10px 0px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ .my_profileimg {
+ width: 56px;
+ height: 56px;
+ border-radius: 50%;
+ }
+
+ .my_info {
+ width: 202px;
+ height: 30px;
+ .mynickname {
+ width: 190px;
+ font-size: 14px;
+ font-weight: bold;
+ margin-left: 12px;
+ color: #262626;
+ }
+
+ .myname {
+ width: 190px;
+ font-size: 14px;
+ margin-left: 12px;
+ color: #8e8e8e;
+ }
+ }
+ .profile_transform {
+ font-weight: 600;
+ font-size: 12px;
+ border: 0;
+ color: #0095f6;
+ }
+ }
+ .recommendation {
+ width: 291px;
+ height: 325px;
+ .recommendation_header {
+ width: 293px;
+ height: 11px;
+ margin-top: 18px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ .recommendation_left {
+ width: 248px;
+ font-size: 14px;
+ color: #8e8e8e;
+ font-weight: 600;
+ }
+
+ .recommendation_right {
+ width: 45px;
+ font-size: 12px;
+ color: #262626;
+ font-weight: 600;
+ }
+ }
+ .recommendation_info {
+ width: 289px;
+ height: 240px;
+ margin-top: 20px;
+ .recommendation_box {
+ width: 289px;
+ margin-bottom: 16px;
+ display: flex;
+ justify-content: space-between;
+ flex-wrap: wrap;
+ align-content: flex-start;
+ .friend_profile {
+ width: 32px;
+ height: 32px;
+ border-radius: 50%;
+ }
+
+ .friend_info {
+ width: 206px;
+ height: 28px;
+ .friend_nickname {
+ width: 205px;
+ color: #262626;
+ font-weight: bold;
+ font-size: 14px;
+ }
+
+ .other_friend {
+ width: 205px;
+ color: #8e8e8e;
+ font-weight: 400;
+ font-size: 12px;
+ }
+ }
+ .follow {
+ height: 15px;
+ font-weight: 600;
+ font-size: 12px;
+ margin-top: 10px;
+ border: 0;
+ color: #0095f6;
+ }
+ }
+ }
+ }
+ aside {
+ width: 293px;
+ height: 68px;
+ .westagram_contents_box {
+ width: 293px;
+ .westagram_contents {
+ color: #c7c7c7;
+ font-size: 11px;
+ font-weight: 400;
+ display: inline;
+ }
+ }
+ .westagram_facebook {
+ width: 205px;
+ color: #c7c7c7;
+ font-size: 11px;
+ font-weight: 400;
+ margin-top: 20px;
+ }
+ }
+}
\ No newline at end of file | Unknown | scss의 nesting을 굉장히 잘 적용하신 것 같아요
이러면 나중에 component단위로 나눌 때 더 편할 것 같습니다! |
@@ -0,0 +1,412 @@
+* {
+ margin: 0;
+ padding: 0;
+}
+nav {
+ position: fixed;
+ width: 100%;
+ top: 0px;
+ left: 0px;
+ right: 0px;
+ background-color: #fff;
+ border-bottom: 1px solid #dbdbdb;
+ .navcontents {
+ width: 935px;
+ height: 54px;
+ background-color: #fff;
+ margin: 0 auto;
+ display: flex;
+ justify-content: space-between;
+ .navleft {
+ width: 360px;
+ .navleftcontents {
+ display: flex;
+ justify-content: flex-start;
+ .logo {
+ font-size: 23px;
+ margin-top: 12px;
+ }
+ .logoname {
+ border-left: 1px solid #bbbbbb;
+ font-family: "Lobster", cursive;
+ margin-left: 15px;
+ margin-top: 7px;
+ padding-left: 15px;
+ }
+ }
+ }
+ .navcenter {
+ width: 215px;
+ .navcentercontents {
+ position: relative;
+ .search {
+ width: 213px;
+ height: 26px;
+ background-color: #fafafa;
+ border: 1px solid #dbdbdb;
+ border-radius: 3px;
+ text-align: center;
+ position: absolute;
+ top: 14px;
+ }
+
+ .searchimg {
+ font-size: 10px;
+ color: #bbbbbb;
+ position: absolute;
+ top: 24px;
+ left: 83px;
+ }
+ }
+ }
+ .navright {
+ width: 360px;
+ .navrightcontents {
+ display: flex;
+ justify-content: flex-end;
+ margin-top: 14px;
+ .navexplore {
+ width: 25px;
+ height: 25px;
+ margin-right: 20px;
+ }
+
+ .navheart {
+ width: 25px;
+ height: 25px;
+ margin-right: 20px;
+ }
+
+ .navprofile {
+ width: 25px;
+ height: 25px;
+ }
+ }
+ }
+ }
+}
+
+
+
+.main {
+ border: 1px solid #fafafa;
+ background-color: #fafafa;
+ .feeds {
+ width: 935px;
+ margin: 0 auto;
+ margin-top: 84px;
+ .story {
+ width: 612px;
+ height: 116px;
+ background-color: #fff;
+ border: 1px solid #dbdbdb;
+ border-radius: 3px;
+ display: flex;
+ align-items: center;
+ .storyimgbox {
+ width: 612px;
+ height: 84px;
+ .storycontents {
+ display: flex;
+ justify-content: space-around;
+ .storylastbox {
+ display: flex;
+ justify-content: center;
+ .storylast {
+ width: 80px;
+ height: 122px;
+ .storyimg1 {
+ width: 56px;
+ height: 56px;
+ border: 1px solid #ececec;
+ border-radius: 50%;
+ padding: 3px;
+ object-fit: cover;
+ }
+
+ .storyp1 {
+ color: #8e8e8e;
+ font-size: 12px;
+ margin-left: 18px;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+
+article {
+ width: 612px;
+ height: auto;
+ background-color: #fff;
+ margin-top: 24px;
+ border: 1px solid #dbdbdb;
+ border-radius: 3px;
+ .articleheader {
+ width: 612px;
+ height: 59px;
+ border: 1px solid #dbdbdb;
+ .articleheadercontents {
+ width: 582px;
+ height: 27px;
+ margin: 15px auto 15px auto;
+ display: flex;
+ justify-content: space-between;
+ .headerimg {
+ width: 32px;
+ height: 32px;
+ border-radius: 50%;
+ object-fit: cover;
+ }
+
+ .headername {
+ width: 536px;
+ height: 26px;
+ .headerlast {
+ height: 26px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ .hname {
+ font-size: 14px;
+ color: #262626;
+ font-weight: bold;
+ }
+ }
+ }
+ }
+ }
+ .articleimg {
+ width: 612px;
+ height: 612px;
+ object-fit: cover;
+ }
+
+ .article_button {
+ width: 582px;
+ height: 49px;
+ margin: 0 auto;
+ display: flex;
+ justify-content: space-between;
+ .article_button_left{
+ .left_button {
+ margin: 8px;
+ }
+ }
+ .article_button_right {
+ .right_button {
+ margin: 8px;
+ }
+ }
+ }
+
+ .number_of_likes {
+ width: 582px;
+ height: 18px;
+ margin: 0 auto;
+ padding-left: 5px;
+ .likes_friend {
+ font-size: 14px;
+ .like_font {
+ color: #262626;
+ font-weight: bold;
+ }
+ }
+ }
+ .friend_comment {
+ width: 582px;
+ height: auto;
+ margin: 0 auto;
+ margin-top: 8px;
+ padding-left: 5px;
+ .explanation {
+ font-size: 14px;
+ .like_font {
+ color: #262626;
+ font-weight: bold;
+ }
+ }
+ .commentBox {
+ list-style: none;
+ }
+ }
+ .time {
+ width: 598px;
+ padding-left: 18px;
+ .a_few_hours_ago {
+ font-size: 10px;
+ color: #8e8e8e;
+ }
+ }
+ .leave_comment_box {
+ border-top: 1px solid #dbdbdb;
+ margin-top: 10px;
+ .leave_comment {
+ width: 582px;
+ height: 55px;
+ margin: 0 auto;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ .smilebox {
+ padding: 8px 15px 8px 0px;
+ }
+ .inputcomment {
+ width: 510px;
+ border: 0;
+ }
+ .inputcomment:focus {
+ outline: none;
+ }
+ .posting_button {
+ background-color: #fff;
+ color: #0095f6;
+ border: 0;
+ }
+ .posting_button:focus{
+ outline: none;
+ }
+ }
+ }
+}
+
+
+
+
+.main-right {
+ width: 293px;
+ height: 612px;
+ position: fixed;
+ top: 85px;
+ left: 885px;
+ .my_profile {
+ width: 293px;
+ height: 56px;
+ margin: 18px 0px 10px 0px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ .my_profileimg {
+ width: 56px;
+ height: 56px;
+ border-radius: 50%;
+ }
+
+ .my_info {
+ width: 202px;
+ height: 30px;
+ .mynickname {
+ width: 190px;
+ font-size: 14px;
+ font-weight: bold;
+ margin-left: 12px;
+ color: #262626;
+ }
+
+ .myname {
+ width: 190px;
+ font-size: 14px;
+ margin-left: 12px;
+ color: #8e8e8e;
+ }
+ }
+ .profile_transform {
+ font-weight: 600;
+ font-size: 12px;
+ border: 0;
+ color: #0095f6;
+ }
+ }
+ .recommendation {
+ width: 291px;
+ height: 325px;
+ .recommendation_header {
+ width: 293px;
+ height: 11px;
+ margin-top: 18px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ .recommendation_left {
+ width: 248px;
+ font-size: 14px;
+ color: #8e8e8e;
+ font-weight: 600;
+ }
+
+ .recommendation_right {
+ width: 45px;
+ font-size: 12px;
+ color: #262626;
+ font-weight: 600;
+ }
+ }
+ .recommendation_info {
+ width: 289px;
+ height: 240px;
+ margin-top: 20px;
+ .recommendation_box {
+ width: 289px;
+ margin-bottom: 16px;
+ display: flex;
+ justify-content: space-between;
+ flex-wrap: wrap;
+ align-content: flex-start;
+ .friend_profile {
+ width: 32px;
+ height: 32px;
+ border-radius: 50%;
+ }
+
+ .friend_info {
+ width: 206px;
+ height: 28px;
+ .friend_nickname {
+ width: 205px;
+ color: #262626;
+ font-weight: bold;
+ font-size: 14px;
+ }
+
+ .other_friend {
+ width: 205px;
+ color: #8e8e8e;
+ font-weight: 400;
+ font-size: 12px;
+ }
+ }
+ .follow {
+ height: 15px;
+ font-weight: 600;
+ font-size: 12px;
+ margin-top: 10px;
+ border: 0;
+ color: #0095f6;
+ }
+ }
+ }
+ }
+ aside {
+ width: 293px;
+ height: 68px;
+ .westagram_contents_box {
+ width: 293px;
+ .westagram_contents {
+ color: #c7c7c7;
+ font-size: 11px;
+ font-weight: 400;
+ display: inline;
+ }
+ }
+ .westagram_facebook {
+ width: 205px;
+ color: #c7c7c7;
+ font-size: 11px;
+ font-weight: 400;
+ margin-top: 20px;
+ }
+ }
+}
\ No newline at end of file | Unknown | ```suggestion
```
빈칸을 줄이는 것도 좋은 습관이라고 하네요! |
@@ -0,0 +1,85 @@
+* {
+ box-sizing: border-box;
+}
+
+.loginContainer {
+ border: 2px solid #e6e6e6;
+ width: 350px;
+ height: 380px;
+ margin: 0 auto;
+ .logoName {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 100%;
+ h1 {
+ font-family: "Lobster", cursive;
+ width: 175px;
+ height: 52px;
+ text-align: center;
+ padding-top: 6px;
+ }
+ }
+ .loginInfo {
+ height: 213px;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ padding-top: 10px;
+ .loginId {
+ width: 268px;
+ height: 38px;
+ margin-bottom: 5px;
+ padding-left: 10px;
+ border-radius: 3px;
+ border: 1px solid #efefef;
+ background: #fafafa;
+ color: #9c9c9c;
+ font-size: 14px;
+ &:focus {
+ outline-color: gray;
+ }
+ }
+ .loginPs {
+ width: 268px;
+ height: 38px;
+ margin-bottom: 5px;
+ padding-left: 10px;
+ border-radius: 3px;
+ border: 1px solid #efefef;
+ background: #fafafa;
+ color: #9c9c9c;
+ font-size: 14px;
+ &:focus {
+ outline-color: gray;
+ }
+ }
+ .loginBt {
+ width: 268px;
+ height: 30px;
+ margin-top: 5px;
+ border-radius: 3px;
+ background-color: #2795f6;
+ color: #ffffff;
+ border-style: none;
+
+ &:focus {
+ outline: none;
+ }
+
+ &:disabled {
+ background-color: #b2dffc;
+ }
+ }
+ }
+ .forgetPassword{
+ display: flex;
+ justify-content: center;
+ margin-top: 20px;
+ a {
+ color: #043569; text-decoration: none;
+ }
+ }
+
+
+} | Unknown | 넘 디테일한 css 속성값 .. 재영님 노고에 경의를..👏🏻 |
@@ -0,0 +1,50 @@
+import React from 'react';
+import { withRouter } from 'react-router-dom';
+import './Login.scss';
+
+
+class LoginJaeyoung extends React.Component {
+ constructor () {
+ super();
+ this.state = {
+ id: '',
+ pw : '',
+ };
+ }
+
+ handleInput = (e) => {
+ const { name,value} = e.target;
+ this.setState({
+ [name]: value
+ })
+ }
+
+ goToMain = () => {
+ this.props.history.push('/main-jaeyoung')
+ }
+
+
+ render () {
+ const { handleInput } = this
+ const isBtnAble = this.state.id.includes('@') && this.state.pw.length >= 5;
+
+
+ return (
+ <div className="loginContainer">
+ <div className="logoName">
+ <h1>Instargram</h1>
+ </div>
+ <div className="loginInfo">
+ <input type="text" name="id" onChange={handleInput} className="loginId" placeholder="전화번호, 사용자 이름 또는 이메일" />
+ <input type="password" name="pw" onChange={handleInput} className="loginPs" placeholder="비밀번호"/>
+ <button className="loginBt" onClick={this.goToMain} disabled={!isBtnAble}>로그인</button>
+ </div>
+ <div className="forgetPassword">
+ <a href="https://www.naver.com/">비밀번호를 잊으셨나요?</a>
+ </div>
+ </div>
+ )
+ }
+}
+
+export default withRouter( LoginJaeyoung );
\ No newline at end of file | JavaScript | target 보다는 직관적인 키네임으로 변경하면 좋을 것 같습니다. |
@@ -0,0 +1,85 @@
+* {
+ box-sizing: border-box;
+}
+
+.loginContainer {
+ border: 2px solid #e6e6e6;
+ width: 350px;
+ height: 380px;
+ margin: 0 auto;
+ .logoName {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 100%;
+ h1 {
+ font-family: "Lobster", cursive;
+ width: 175px;
+ height: 52px;
+ text-align: center;
+ padding-top: 6px;
+ }
+ }
+ .loginInfo {
+ height: 213px;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ padding-top: 10px;
+ .loginId {
+ width: 268px;
+ height: 38px;
+ margin-bottom: 5px;
+ padding-left: 10px;
+ border-radius: 3px;
+ border: 1px solid #efefef;
+ background: #fafafa;
+ color: #9c9c9c;
+ font-size: 14px;
+ &:focus {
+ outline-color: gray;
+ }
+ }
+ .loginPs {
+ width: 268px;
+ height: 38px;
+ margin-bottom: 5px;
+ padding-left: 10px;
+ border-radius: 3px;
+ border: 1px solid #efefef;
+ background: #fafafa;
+ color: #9c9c9c;
+ font-size: 14px;
+ &:focus {
+ outline-color: gray;
+ }
+ }
+ .loginBt {
+ width: 268px;
+ height: 30px;
+ margin-top: 5px;
+ border-radius: 3px;
+ background-color: #2795f6;
+ color: #ffffff;
+ border-style: none;
+
+ &:focus {
+ outline: none;
+ }
+
+ &:disabled {
+ background-color: #b2dffc;
+ }
+ }
+ }
+ .forgetPassword{
+ display: flex;
+ justify-content: center;
+ margin-top: 20px;
+ a {
+ color: #043569; text-decoration: none;
+ }
+ }
+
+
+} | Unknown | - 하나의 요소에 여러가지 속성을 부여하는 경우 중요도, 관련도에 따라서 나름의 convention을 지켜서 작성하는 것이 좋습니다.
- 일반적인 convention 은 아래와 같습니다. 아래와 같이 순서 적용해주세요.
[CSS property 순서]
- Layout Properties (position, float, clear, display)
- Box Model Properties (width, height, margin, padding)
- Visual Properties (color, background, border, box-shadow)
- Typography Properties (font-size, font-family, text-align, text-transform)
- Misc Properties (cursor, overflow, z-index) |
@@ -3,7 +3,10 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>React App</title>
+ <meta name="description" content="Web site created using create-react-app"/>
+ <link href="https://fonts.googleapis.com/css2?family=Lobster&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
+ <title>Westagram</title>
</head>
<body>
<div id="root"></div> | Unknown | meta 태그의 종류가 많기 대문에 어떤 데이터인지 명시하는 차원에서는 있는 것이 좋을 것 같습니다! |
@@ -3,7 +3,10 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>React App</title>
+ <meta name="description" content="Web site created using create-react-app"/>
+ <link href="https://fonts.googleapis.com/css2?family=Lobster&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
+ <title>Westagram</title>
</head>
<body>
<div id="root"></div> | Unknown | 불필요한 엔터 처리는 삭제해주세요! |
@@ -0,0 +1,50 @@
+import React from 'react';
+import { withRouter } from 'react-router-dom';
+import './Login.scss';
+
+
+class LoginJaeyoung extends React.Component {
+ constructor () {
+ super();
+ this.state = {
+ id: '',
+ pw : '',
+ };
+ }
+
+ handleInput = (e) => {
+ const { name,value} = e.target;
+ this.setState({
+ [name]: value
+ })
+ }
+
+ goToMain = () => {
+ this.props.history.push('/main-jaeyoung')
+ }
+
+
+ render () {
+ const { handleInput } = this
+ const isBtnAble = this.state.id.includes('@') && this.state.pw.length >= 5;
+
+
+ return (
+ <div className="loginContainer">
+ <div className="logoName">
+ <h1>Instargram</h1>
+ </div>
+ <div className="loginInfo">
+ <input type="text" name="id" onChange={handleInput} className="loginId" placeholder="전화번호, 사용자 이름 또는 이메일" />
+ <input type="password" name="pw" onChange={handleInput} className="loginPs" placeholder="비밀번호"/>
+ <button className="loginBt" onClick={this.goToMain} disabled={!isBtnAble}>로그인</button>
+ </div>
+ <div className="forgetPassword">
+ <a href="https://www.naver.com/">비밀번호를 잊으셨나요?</a>
+ </div>
+ </div>
+ )
+ }
+}
+
+export default withRouter( LoginJaeyoung );
\ No newline at end of file | JavaScript | Import 순서 수정해주세요! 일반적인 convention을 따르는 이유도 있지만 순서만 잘 지켜주셔도 가독성이 좋아집니다. 아래 순서 참고해주세요.
- React → Library(Package) → Component → 변수 / 이미지 → css 파일(scss 파일) |
@@ -0,0 +1,50 @@
+import React from 'react';
+import { withRouter } from 'react-router-dom';
+import './Login.scss';
+
+
+class LoginJaeyoung extends React.Component {
+ constructor () {
+ super();
+ this.state = {
+ id: '',
+ pw : '',
+ };
+ }
+
+ handleInput = (e) => {
+ const { name,value} = e.target;
+ this.setState({
+ [name]: value
+ })
+ }
+
+ goToMain = () => {
+ this.props.history.push('/main-jaeyoung')
+ }
+
+
+ render () {
+ const { handleInput } = this
+ const isBtnAble = this.state.id.includes('@') && this.state.pw.length >= 5;
+
+
+ return (
+ <div className="loginContainer">
+ <div className="logoName">
+ <h1>Instargram</h1>
+ </div>
+ <div className="loginInfo">
+ <input type="text" name="id" onChange={handleInput} className="loginId" placeholder="전화번호, 사용자 이름 또는 이메일" />
+ <input type="password" name="pw" onChange={handleInput} className="loginPs" placeholder="비밀번호"/>
+ <button className="loginBt" onClick={this.goToMain} disabled={!isBtnAble}>로그인</button>
+ </div>
+ <div className="forgetPassword">
+ <a href="https://www.naver.com/">비밀번호를 잊으셨나요?</a>
+ </div>
+ </div>
+ )
+ }
+}
+
+export default withRouter( LoginJaeyoung );
\ No newline at end of file | JavaScript | ```js
// render 아래에서
const isBtnAble = idValue.includes('@') && psValue.length > 5;
<button disabled={!isBtnAble} />
```
- 이런식으로 변수를 활용하면 좀 더 깔끔해질 수 있겠네요!
- Boolean 데이터를 사용하는 경우에는 굳이 true, false 표시해줄 필요 없습니다! (삼항 연산자 조건에 해당되는 부분이 이미 t/f 값을 갖기 때문에) |
@@ -0,0 +1,85 @@
+* {
+ box-sizing: border-box;
+}
+
+.loginContainer {
+ border: 2px solid #e6e6e6;
+ width: 350px;
+ height: 380px;
+ margin: 0 auto;
+ .logoName {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 100%;
+ h1 {
+ font-family: "Lobster", cursive;
+ width: 175px;
+ height: 52px;
+ text-align: center;
+ padding-top: 6px;
+ }
+ }
+ .loginInfo {
+ height: 213px;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ padding-top: 10px;
+ .loginId {
+ width: 268px;
+ height: 38px;
+ margin-bottom: 5px;
+ padding-left: 10px;
+ border-radius: 3px;
+ border: 1px solid #efefef;
+ background: #fafafa;
+ color: #9c9c9c;
+ font-size: 14px;
+ &:focus {
+ outline-color: gray;
+ }
+ }
+ .loginPs {
+ width: 268px;
+ height: 38px;
+ margin-bottom: 5px;
+ padding-left: 10px;
+ border-radius: 3px;
+ border: 1px solid #efefef;
+ background: #fafafa;
+ color: #9c9c9c;
+ font-size: 14px;
+ &:focus {
+ outline-color: gray;
+ }
+ }
+ .loginBt {
+ width: 268px;
+ height: 30px;
+ margin-top: 5px;
+ border-radius: 3px;
+ background-color: #2795f6;
+ color: #ffffff;
+ border-style: none;
+
+ &:focus {
+ outline: none;
+ }
+
+ &:disabled {
+ background-color: #b2dffc;
+ }
+ }
+ }
+ .forgetPassword{
+ display: flex;
+ justify-content: center;
+ margin-top: 20px;
+ a {
+ color: #043569; text-decoration: none;
+ }
+ }
+
+
+} | Unknown | 가독성을 위해 selector 사이에 한 줄 띄워주시면 좋습니다. |
@@ -0,0 +1,85 @@
+* {
+ box-sizing: border-box;
+}
+
+.loginContainer {
+ border: 2px solid #e6e6e6;
+ width: 350px;
+ height: 380px;
+ margin: 0 auto;
+ .logoName {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 100%;
+ h1 {
+ font-family: "Lobster", cursive;
+ width: 175px;
+ height: 52px;
+ text-align: center;
+ padding-top: 6px;
+ }
+ }
+ .loginInfo {
+ height: 213px;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ padding-top: 10px;
+ .loginId {
+ width: 268px;
+ height: 38px;
+ margin-bottom: 5px;
+ padding-left: 10px;
+ border-radius: 3px;
+ border: 1px solid #efefef;
+ background: #fafafa;
+ color: #9c9c9c;
+ font-size: 14px;
+ &:focus {
+ outline-color: gray;
+ }
+ }
+ .loginPs {
+ width: 268px;
+ height: 38px;
+ margin-bottom: 5px;
+ padding-left: 10px;
+ border-radius: 3px;
+ border: 1px solid #efefef;
+ background: #fafafa;
+ color: #9c9c9c;
+ font-size: 14px;
+ &:focus {
+ outline-color: gray;
+ }
+ }
+ .loginBt {
+ width: 268px;
+ height: 30px;
+ margin-top: 5px;
+ border-radius: 3px;
+ background-color: #2795f6;
+ color: #ffffff;
+ border-style: none;
+
+ &:focus {
+ outline: none;
+ }
+
+ &:disabled {
+ background-color: #b2dffc;
+ }
+ }
+ }
+ .forgetPassword{
+ display: flex;
+ justify-content: center;
+ margin-top: 20px;
+ a {
+ color: #043569; text-decoration: none;
+ }
+ }
+
+
+} | Unknown | 공통되는 속성이 많이 보이네요! 줄여봅시다 🙌 하나의 요소에 복수의 className을 부여할 수 있습니다. |
@@ -0,0 +1,190 @@
+import React from 'react';
+import FeedComponent from './FeedComponent/FeedComponent';
+import './Main.scss';
+import explore from '../../../images/jaeyoungLee/Main/explore.jpg';
+import heart from '../../../images/jaeyoungLee/Main/heart.jpg';
+import profile from '../../../images/jaeyoungLee/Main/profile.jpg';
+import heungminSon from '../../../images/jaeyoungLee/Main/손흥민.jpg';
+class MainJaeyoung extends React.Component {
+ constructor () {
+ super();
+ this.state = {
+ commentFeed : [],
+ }
+ }
+
+ componentDidMount() {
+ fetch('http://localhost:3000/data/feedData.json', {
+ method: 'GET'
+ })
+ .then(res => res.json())
+ .then(data => {
+ this.setState({
+ commentFeed: data,
+ });
+ });
+ }
+
+
+
+ render(){
+ const { commentFeed } = this.state;
+ return(
+ <>
+ <nav>
+ <div className="navcontents">
+ <div className="navleft">
+ <div className="navleftcontents">
+ <span className="logo"><i className="fab fa-instagram"></i></span>
+ <h1 className="logoname">westagram</h1>
+ </div>
+ </div>
+ <div className="navcenter">
+ <div className="navcentercontents">
+ <input className="search" type="text" placeholder="검색"/>
+ <span className="searchimg"><i className="fas fa-search"></i></span>
+ </div>
+ </div>
+ <div className="navright">
+ <div className="navrightcontents">
+ <img className="navexplore" src={explore} alt="탐험"/>
+ <img className="navheart" src={heart} alt="하트"/>
+ <img className="navprofile" src={profile} alt="프로필"/>
+ </div>
+ </div>
+ </div>
+ </nav>
+ <div className="main">
+ <div className="feeds">
+ <div className="story">
+ <div className="storyimgbox">
+ <div className="storycontents">
+ <div className="storyprofile">
+ <div className="storylastbox">
+ <div className="storylast">
+ <img className="storyimg1" src={heungminSon} alt="프로필1"/>
+ <p className="storyp1">손흥민</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://instagram.famm6-1.fna.fbcdn.net/v/t51.2885-19/44884218_345707102882519_2446069589734326272_n.jpg?_nc_ht=instagram.famm6-1.fna.fbcdn.net&_nc_ohc=mhDR9_0DpXIAX_KX0iq&ccb=7-4&oh=dcbb150241d6b1336dd54a4a20417b2a&oe=608B680F&_nc_sid=712cc3&ig_cache_key=YW5vbnltb3VzX3Byb2ZpbGVfcGlj.2-ccb7-4" alt="프로필1"/>
+ <p className="storyp1">2wo0</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/35999304_258159611658935_7092278198804676608_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=et4sZhNbgpAAX-qKBH9&ccb=7-4&oh=0b254f6fb3e4182513c3e20ed1a326d0&oe=608BC5C1&_nc_sid=48a2a6" alt="프로필1"/>
+ <p className="storyp1">geg</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/150675895_144233967522798_7515094658452540248_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=xslO4Za0644AX9cwObZ&ccb=7-4&oh=0f5cb82fd80b51b47d74e160e228aa1c&oe=608D7B5E&_nc_sid=48a2a6" alt="프로필1"/>
+ <p className="storyp1">h._.j</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/135771971_1881013862054625_6713353513169410837_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=SxJIiqRh4rcAX8RSLYk&ccb=7-4&oh=6dec08c37a69cb2c2a14f21bc36b5eef&oe=608C0912&_nc_sid=48a2a6" alt="프로필1"/>
+ <p className="storyp1">idon</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/155951500_335125831259326_3729086392261698560_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=3nnTQdlVU98AX_4fVMv&ccb=7-4&oh=4a596fc0e33f2ece37634ae50d38cdde&oe=608C5901&_nc_sid=48a2a6" alt="프로필1"/>
+ <p className="storyp1">dfewg</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/37828240_293117218102022_6759937585105076224_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=jzs6QvrGtHAAX_qFR80&ccb=7-4&oh=f4984cbce61bc445f02622a5468278b3&oe=608B09A1&_nc_sid=57d425" alt="프로필1"/>
+ <p className="storyp1">33gg</p>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ {commentFeed.map((feed,id) =>{
+ return (
+ <FeedComponent key={feed.id} profileimg={feed.profileimg} userName={feed.userName} feedimg={feed.feedimg} feedcontent={feed.feedcontent} />
+ );
+ })}
+
+ </div>
+ <div className="main-right">
+ <div className="my_profile">
+ <img className="my_profileimg" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/141997127_1523884024669097_6148385093252095280_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=ldPmBqcpW3kAX9esSCC&ccb=7-4&oh=6503a99b1b0096ad362012fef7e72aed&oe=6085537E&_nc_sid=7b02f1" alt="프로필"/>
+ <div className="my_info">
+ <p className="mynickname">2wo0_0</p>
+ <p className="myname">이재영</p>
+ </div>
+ <button className="profile_transform" disabled>전환</button>
+ </div>
+ <div className="recommendation">
+ <div className="recommendation_header">
+ <p className="recommendation_left">회원님을 위한 추천</p>
+ <p className="recommendation_right">모두 보기</p>
+ </div>
+ <div className="recommendation_info">
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/156650140_116853317083347_8770042214751161261_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=-evbCZABANYAX_WcDzP&edm=AEF8tYYAAAAA&ccb=7-4&oh=5eb6e52a64b2ad8c98bff45dab473831&oe=60880D5B&_nc_sid=a9513d" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">ryu_d_g</p>
+ <p className="other_friend">1996yunsi님 외 13명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/159992110_105322351555148_1839915921172216453_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=xfLIvYCwwiIAX8AJI08&ccb=7-4&oh=7bdaf0e022e88f0dd5079c1995892031&oe=608D9B9E&_nc_sid=57d425" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">2s2_f</p>
+ <p className="other_friend">_sihyeon___님 외 49명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/160716680_272942871038831_8108440433038115559_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=VmeF5WmeLg4AX-jiUAL&ccb=7-4&oh=cf29d0253e8afb755a9d26ad13a6deda&oe=608D4A0C&_nc_sid=a9513d" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">rdfe_g</p>
+ <p className="other_friend">111_fkdn님 외 5명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/164274433_776408706413539_3215024154205561736_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=gCCfowKp9OMAX9_NBIP&ccb=7-4&oh=afbada353869184275b4d3be70f38605&oe=608BE909&_nc_sid=a9513d" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">cat_2d_g</p>
+ <p className="other_friend">cjdtkseh님 외 15명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src=" https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/164520013_834814623778500_398528442563386719_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=iLm66uEJKQ4AX88GkVl&ccb=7-4&oh=4fe271ebb6f627b328cb3d24bb811776&oe=608E6098&_nc_sid=86f79a" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">tksdkdnENr</p>
+ <p className="other_friend">cjfcjfgme1님 외 32명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ </div>
+ </div>
+ <aside>
+ <ul className="westagram_contents_box">
+ {CONTENTS.map((el,id) =>
+ <li key={id} className="westagram_contents">{el.content}</li>
+ )}
+
+ </ul>
+ <p className="westagram_facebook">© 2021 INSTAGRAM FROM FACEBOOK</p>
+ </aside>
+ </div>
+ </div>
+ </>
+ )
+ }
+}
+export default MainJaeyoung ;
+
+const CONTENTS = [
+ {id: 1, content: "소개"},
+ {id: 2, content: "도움말"},
+ {id: 3, content: "홍보 센터"},
+ {id: 4, content: "API"},
+ {id: 5, content: "채용정보"},
+ {id: 6, content: "개인정보처리방침"},
+ {id: 7, content: "약관"},
+ {id: 8, content: "위치"},
+ {id: 9, content: "인기 계정"},
+ {id: 10, content: "해시태그"},
+ {id: 11, content: "언어"},
+]
\ No newline at end of file | JavaScript | addComment와 같이 기능의 의미가 들어나는 이름으로 함수명을 작성해주세요! |
@@ -0,0 +1,190 @@
+import React from 'react';
+import FeedComponent from './FeedComponent/FeedComponent';
+import './Main.scss';
+import explore from '../../../images/jaeyoungLee/Main/explore.jpg';
+import heart from '../../../images/jaeyoungLee/Main/heart.jpg';
+import profile from '../../../images/jaeyoungLee/Main/profile.jpg';
+import heungminSon from '../../../images/jaeyoungLee/Main/손흥민.jpg';
+class MainJaeyoung extends React.Component {
+ constructor () {
+ super();
+ this.state = {
+ commentFeed : [],
+ }
+ }
+
+ componentDidMount() {
+ fetch('http://localhost:3000/data/feedData.json', {
+ method: 'GET'
+ })
+ .then(res => res.json())
+ .then(data => {
+ this.setState({
+ commentFeed: data,
+ });
+ });
+ }
+
+
+
+ render(){
+ const { commentFeed } = this.state;
+ return(
+ <>
+ <nav>
+ <div className="navcontents">
+ <div className="navleft">
+ <div className="navleftcontents">
+ <span className="logo"><i className="fab fa-instagram"></i></span>
+ <h1 className="logoname">westagram</h1>
+ </div>
+ </div>
+ <div className="navcenter">
+ <div className="navcentercontents">
+ <input className="search" type="text" placeholder="검색"/>
+ <span className="searchimg"><i className="fas fa-search"></i></span>
+ </div>
+ </div>
+ <div className="navright">
+ <div className="navrightcontents">
+ <img className="navexplore" src={explore} alt="탐험"/>
+ <img className="navheart" src={heart} alt="하트"/>
+ <img className="navprofile" src={profile} alt="프로필"/>
+ </div>
+ </div>
+ </div>
+ </nav>
+ <div className="main">
+ <div className="feeds">
+ <div className="story">
+ <div className="storyimgbox">
+ <div className="storycontents">
+ <div className="storyprofile">
+ <div className="storylastbox">
+ <div className="storylast">
+ <img className="storyimg1" src={heungminSon} alt="프로필1"/>
+ <p className="storyp1">손흥민</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://instagram.famm6-1.fna.fbcdn.net/v/t51.2885-19/44884218_345707102882519_2446069589734326272_n.jpg?_nc_ht=instagram.famm6-1.fna.fbcdn.net&_nc_ohc=mhDR9_0DpXIAX_KX0iq&ccb=7-4&oh=dcbb150241d6b1336dd54a4a20417b2a&oe=608B680F&_nc_sid=712cc3&ig_cache_key=YW5vbnltb3VzX3Byb2ZpbGVfcGlj.2-ccb7-4" alt="프로필1"/>
+ <p className="storyp1">2wo0</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/35999304_258159611658935_7092278198804676608_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=et4sZhNbgpAAX-qKBH9&ccb=7-4&oh=0b254f6fb3e4182513c3e20ed1a326d0&oe=608BC5C1&_nc_sid=48a2a6" alt="프로필1"/>
+ <p className="storyp1">geg</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/150675895_144233967522798_7515094658452540248_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=xslO4Za0644AX9cwObZ&ccb=7-4&oh=0f5cb82fd80b51b47d74e160e228aa1c&oe=608D7B5E&_nc_sid=48a2a6" alt="프로필1"/>
+ <p className="storyp1">h._.j</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/135771971_1881013862054625_6713353513169410837_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=SxJIiqRh4rcAX8RSLYk&ccb=7-4&oh=6dec08c37a69cb2c2a14f21bc36b5eef&oe=608C0912&_nc_sid=48a2a6" alt="프로필1"/>
+ <p className="storyp1">idon</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/155951500_335125831259326_3729086392261698560_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=3nnTQdlVU98AX_4fVMv&ccb=7-4&oh=4a596fc0e33f2ece37634ae50d38cdde&oe=608C5901&_nc_sid=48a2a6" alt="프로필1"/>
+ <p className="storyp1">dfewg</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/37828240_293117218102022_6759937585105076224_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=jzs6QvrGtHAAX_qFR80&ccb=7-4&oh=f4984cbce61bc445f02622a5468278b3&oe=608B09A1&_nc_sid=57d425" alt="프로필1"/>
+ <p className="storyp1">33gg</p>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ {commentFeed.map((feed,id) =>{
+ return (
+ <FeedComponent key={feed.id} profileimg={feed.profileimg} userName={feed.userName} feedimg={feed.feedimg} feedcontent={feed.feedcontent} />
+ );
+ })}
+
+ </div>
+ <div className="main-right">
+ <div className="my_profile">
+ <img className="my_profileimg" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/141997127_1523884024669097_6148385093252095280_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=ldPmBqcpW3kAX9esSCC&ccb=7-4&oh=6503a99b1b0096ad362012fef7e72aed&oe=6085537E&_nc_sid=7b02f1" alt="프로필"/>
+ <div className="my_info">
+ <p className="mynickname">2wo0_0</p>
+ <p className="myname">이재영</p>
+ </div>
+ <button className="profile_transform" disabled>전환</button>
+ </div>
+ <div className="recommendation">
+ <div className="recommendation_header">
+ <p className="recommendation_left">회원님을 위한 추천</p>
+ <p className="recommendation_right">모두 보기</p>
+ </div>
+ <div className="recommendation_info">
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/156650140_116853317083347_8770042214751161261_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=-evbCZABANYAX_WcDzP&edm=AEF8tYYAAAAA&ccb=7-4&oh=5eb6e52a64b2ad8c98bff45dab473831&oe=60880D5B&_nc_sid=a9513d" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">ryu_d_g</p>
+ <p className="other_friend">1996yunsi님 외 13명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/159992110_105322351555148_1839915921172216453_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=xfLIvYCwwiIAX8AJI08&ccb=7-4&oh=7bdaf0e022e88f0dd5079c1995892031&oe=608D9B9E&_nc_sid=57d425" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">2s2_f</p>
+ <p className="other_friend">_sihyeon___님 외 49명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/160716680_272942871038831_8108440433038115559_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=VmeF5WmeLg4AX-jiUAL&ccb=7-4&oh=cf29d0253e8afb755a9d26ad13a6deda&oe=608D4A0C&_nc_sid=a9513d" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">rdfe_g</p>
+ <p className="other_friend">111_fkdn님 외 5명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/164274433_776408706413539_3215024154205561736_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=gCCfowKp9OMAX9_NBIP&ccb=7-4&oh=afbada353869184275b4d3be70f38605&oe=608BE909&_nc_sid=a9513d" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">cat_2d_g</p>
+ <p className="other_friend">cjdtkseh님 외 15명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src=" https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/164520013_834814623778500_398528442563386719_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=iLm66uEJKQ4AX88GkVl&ccb=7-4&oh=4fe271ebb6f627b328cb3d24bb811776&oe=608E6098&_nc_sid=86f79a" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">tksdkdnENr</p>
+ <p className="other_friend">cjfcjfgme1님 외 32명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ </div>
+ </div>
+ <aside>
+ <ul className="westagram_contents_box">
+ {CONTENTS.map((el,id) =>
+ <li key={id} className="westagram_contents">{el.content}</li>
+ )}
+
+ </ul>
+ <p className="westagram_facebook">© 2021 INSTAGRAM FROM FACEBOOK</p>
+ </aside>
+ </div>
+ </div>
+ </>
+ )
+ }
+}
+export default MainJaeyoung ;
+
+const CONTENTS = [
+ {id: 1, content: "소개"},
+ {id: 2, content: "도움말"},
+ {id: 3, content: "홍보 센터"},
+ {id: 4, content: "API"},
+ {id: 5, content: "채용정보"},
+ {id: 6, content: "개인정보처리방침"},
+ {id: 7, content: "약관"},
+ {id: 8, content: "위치"},
+ {id: 9, content: "인기 계정"},
+ {id: 10, content: "해시태그"},
+ {id: 11, content: "언어"},
+]
\ No newline at end of file | JavaScript | - 해당 파일에 데이터를 배열로 만들어서 map 함수 적용하면 좋을 부분이 많이 보이네요! 우선 이 것 부터 수정해보시기 바랍니다.
- https://www.notion.so/wecode/React-Refactoring-Check-List-aea297cf88ed4601b769e4b2c2cfd4e1#ef5cf308f13f48458f69175875c239e9 |
@@ -0,0 +1,17 @@
+import React from 'react';
+import './CommentComponent.scss';
+
+class CommentComponent extends React.Component {
+ render() {
+ const { key, name, comment} = this.props
+ return (
+ <li className="CommentComponent">
+ {key}
+ <strong>{name}</strong>
+ {comment}
+ </li>
+ )
+ }
+}
+
+export default CommentComponent;
\ No newline at end of file | JavaScript | commentList는 ul 태그를 의미하는 것 같아서 props 이름을 comment로 하는게 좋을 것 같습니다. |
@@ -0,0 +1,412 @@
+* {
+ margin: 0;
+ padding: 0;
+}
+nav {
+ position: fixed;
+ width: 100%;
+ top: 0px;
+ left: 0px;
+ right: 0px;
+ background-color: #fff;
+ border-bottom: 1px solid #dbdbdb;
+ .navcontents {
+ width: 935px;
+ height: 54px;
+ background-color: #fff;
+ margin: 0 auto;
+ display: flex;
+ justify-content: space-between;
+ .navleft {
+ width: 360px;
+ .navleftcontents {
+ display: flex;
+ justify-content: flex-start;
+ .logo {
+ font-size: 23px;
+ margin-top: 12px;
+ }
+ .logoname {
+ border-left: 1px solid #bbbbbb;
+ font-family: "Lobster", cursive;
+ margin-left: 15px;
+ margin-top: 7px;
+ padding-left: 15px;
+ }
+ }
+ }
+ .navcenter {
+ width: 215px;
+ .navcentercontents {
+ position: relative;
+ .search {
+ width: 213px;
+ height: 26px;
+ background-color: #fafafa;
+ border: 1px solid #dbdbdb;
+ border-radius: 3px;
+ text-align: center;
+ position: absolute;
+ top: 14px;
+ }
+
+ .searchimg {
+ font-size: 10px;
+ color: #bbbbbb;
+ position: absolute;
+ top: 24px;
+ left: 83px;
+ }
+ }
+ }
+ .navright {
+ width: 360px;
+ .navrightcontents {
+ display: flex;
+ justify-content: flex-end;
+ margin-top: 14px;
+ .navexplore {
+ width: 25px;
+ height: 25px;
+ margin-right: 20px;
+ }
+
+ .navheart {
+ width: 25px;
+ height: 25px;
+ margin-right: 20px;
+ }
+
+ .navprofile {
+ width: 25px;
+ height: 25px;
+ }
+ }
+ }
+ }
+}
+
+
+
+.main {
+ border: 1px solid #fafafa;
+ background-color: #fafafa;
+ .feeds {
+ width: 935px;
+ margin: 0 auto;
+ margin-top: 84px;
+ .story {
+ width: 612px;
+ height: 116px;
+ background-color: #fff;
+ border: 1px solid #dbdbdb;
+ border-radius: 3px;
+ display: flex;
+ align-items: center;
+ .storyimgbox {
+ width: 612px;
+ height: 84px;
+ .storycontents {
+ display: flex;
+ justify-content: space-around;
+ .storylastbox {
+ display: flex;
+ justify-content: center;
+ .storylast {
+ width: 80px;
+ height: 122px;
+ .storyimg1 {
+ width: 56px;
+ height: 56px;
+ border: 1px solid #ececec;
+ border-radius: 50%;
+ padding: 3px;
+ object-fit: cover;
+ }
+
+ .storyp1 {
+ color: #8e8e8e;
+ font-size: 12px;
+ margin-left: 18px;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+
+article {
+ width: 612px;
+ height: auto;
+ background-color: #fff;
+ margin-top: 24px;
+ border: 1px solid #dbdbdb;
+ border-radius: 3px;
+ .articleheader {
+ width: 612px;
+ height: 59px;
+ border: 1px solid #dbdbdb;
+ .articleheadercontents {
+ width: 582px;
+ height: 27px;
+ margin: 15px auto 15px auto;
+ display: flex;
+ justify-content: space-between;
+ .headerimg {
+ width: 32px;
+ height: 32px;
+ border-radius: 50%;
+ object-fit: cover;
+ }
+
+ .headername {
+ width: 536px;
+ height: 26px;
+ .headerlast {
+ height: 26px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ .hname {
+ font-size: 14px;
+ color: #262626;
+ font-weight: bold;
+ }
+ }
+ }
+ }
+ }
+ .articleimg {
+ width: 612px;
+ height: 612px;
+ object-fit: cover;
+ }
+
+ .article_button {
+ width: 582px;
+ height: 49px;
+ margin: 0 auto;
+ display: flex;
+ justify-content: space-between;
+ .article_button_left{
+ .left_button {
+ margin: 8px;
+ }
+ }
+ .article_button_right {
+ .right_button {
+ margin: 8px;
+ }
+ }
+ }
+
+ .number_of_likes {
+ width: 582px;
+ height: 18px;
+ margin: 0 auto;
+ padding-left: 5px;
+ .likes_friend {
+ font-size: 14px;
+ .like_font {
+ color: #262626;
+ font-weight: bold;
+ }
+ }
+ }
+ .friend_comment {
+ width: 582px;
+ height: auto;
+ margin: 0 auto;
+ margin-top: 8px;
+ padding-left: 5px;
+ .explanation {
+ font-size: 14px;
+ .like_font {
+ color: #262626;
+ font-weight: bold;
+ }
+ }
+ .commentBox {
+ list-style: none;
+ }
+ }
+ .time {
+ width: 598px;
+ padding-left: 18px;
+ .a_few_hours_ago {
+ font-size: 10px;
+ color: #8e8e8e;
+ }
+ }
+ .leave_comment_box {
+ border-top: 1px solid #dbdbdb;
+ margin-top: 10px;
+ .leave_comment {
+ width: 582px;
+ height: 55px;
+ margin: 0 auto;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ .smilebox {
+ padding: 8px 15px 8px 0px;
+ }
+ .inputcomment {
+ width: 510px;
+ border: 0;
+ }
+ .inputcomment:focus {
+ outline: none;
+ }
+ .posting_button {
+ background-color: #fff;
+ color: #0095f6;
+ border: 0;
+ }
+ .posting_button:focus{
+ outline: none;
+ }
+ }
+ }
+}
+
+
+
+
+.main-right {
+ width: 293px;
+ height: 612px;
+ position: fixed;
+ top: 85px;
+ left: 885px;
+ .my_profile {
+ width: 293px;
+ height: 56px;
+ margin: 18px 0px 10px 0px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ .my_profileimg {
+ width: 56px;
+ height: 56px;
+ border-radius: 50%;
+ }
+
+ .my_info {
+ width: 202px;
+ height: 30px;
+ .mynickname {
+ width: 190px;
+ font-size: 14px;
+ font-weight: bold;
+ margin-left: 12px;
+ color: #262626;
+ }
+
+ .myname {
+ width: 190px;
+ font-size: 14px;
+ margin-left: 12px;
+ color: #8e8e8e;
+ }
+ }
+ .profile_transform {
+ font-weight: 600;
+ font-size: 12px;
+ border: 0;
+ color: #0095f6;
+ }
+ }
+ .recommendation {
+ width: 291px;
+ height: 325px;
+ .recommendation_header {
+ width: 293px;
+ height: 11px;
+ margin-top: 18px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ .recommendation_left {
+ width: 248px;
+ font-size: 14px;
+ color: #8e8e8e;
+ font-weight: 600;
+ }
+
+ .recommendation_right {
+ width: 45px;
+ font-size: 12px;
+ color: #262626;
+ font-weight: 600;
+ }
+ }
+ .recommendation_info {
+ width: 289px;
+ height: 240px;
+ margin-top: 20px;
+ .recommendation_box {
+ width: 289px;
+ margin-bottom: 16px;
+ display: flex;
+ justify-content: space-between;
+ flex-wrap: wrap;
+ align-content: flex-start;
+ .friend_profile {
+ width: 32px;
+ height: 32px;
+ border-radius: 50%;
+ }
+
+ .friend_info {
+ width: 206px;
+ height: 28px;
+ .friend_nickname {
+ width: 205px;
+ color: #262626;
+ font-weight: bold;
+ font-size: 14px;
+ }
+
+ .other_friend {
+ width: 205px;
+ color: #8e8e8e;
+ font-weight: 400;
+ font-size: 12px;
+ }
+ }
+ .follow {
+ height: 15px;
+ font-weight: 600;
+ font-size: 12px;
+ margin-top: 10px;
+ border: 0;
+ color: #0095f6;
+ }
+ }
+ }
+ }
+ aside {
+ width: 293px;
+ height: 68px;
+ .westagram_contents_box {
+ width: 293px;
+ .westagram_contents {
+ color: #c7c7c7;
+ font-size: 11px;
+ font-weight: 400;
+ display: inline;
+ }
+ }
+ .westagram_facebook {
+ width: 205px;
+ color: #c7c7c7;
+ font-size: 11px;
+ font-weight: 400;
+ margin-top: 20px;
+ }
+ }
+}
\ No newline at end of file | Unknown | 전체적으로 camelCase, snake_case 혼용해서 사용하고 계신데 다음에는 팀원들과 정한 규칙대로 적용해주세요! 최소한 내가 작성한 코드 안에서는 일관성이 있어야 합니다. |
@@ -0,0 +1,85 @@
+* {
+ box-sizing: border-box;
+}
+
+.loginContainer {
+ border: 2px solid #e6e6e6;
+ width: 350px;
+ height: 380px;
+ margin: 0 auto;
+ .logoName {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 100%;
+ h1 {
+ font-family: "Lobster", cursive;
+ width: 175px;
+ height: 52px;
+ text-align: center;
+ padding-top: 6px;
+ }
+ }
+ .loginInfo {
+ height: 213px;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ padding-top: 10px;
+ .loginId {
+ width: 268px;
+ height: 38px;
+ margin-bottom: 5px;
+ padding-left: 10px;
+ border-radius: 3px;
+ border: 1px solid #efefef;
+ background: #fafafa;
+ color: #9c9c9c;
+ font-size: 14px;
+ &:focus {
+ outline-color: gray;
+ }
+ }
+ .loginPs {
+ width: 268px;
+ height: 38px;
+ margin-bottom: 5px;
+ padding-left: 10px;
+ border-radius: 3px;
+ border: 1px solid #efefef;
+ background: #fafafa;
+ color: #9c9c9c;
+ font-size: 14px;
+ &:focus {
+ outline-color: gray;
+ }
+ }
+ .loginBt {
+ width: 268px;
+ height: 30px;
+ margin-top: 5px;
+ border-radius: 3px;
+ background-color: #2795f6;
+ color: #ffffff;
+ border-style: none;
+
+ &:focus {
+ outline: none;
+ }
+
+ &:disabled {
+ background-color: #b2dffc;
+ }
+ }
+ }
+ .forgetPassword{
+ display: flex;
+ justify-content: center;
+ margin-top: 20px;
+ a {
+ color: #043569; text-decoration: none;
+ }
+ }
+
+
+} | Unknown | 넵! 알겠습니다! |
@@ -3,7 +3,10 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>React App</title>
+ <meta name="description" content="Web site created using create-react-app"/>
+ <link href="https://fonts.googleapis.com/css2?family=Lobster&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
+ <title>Westagram</title>
</head>
<body>
<div id="root"></div> | Unknown | 삭제했습니다! 감사합니다 |
@@ -0,0 +1,50 @@
+import React from 'react';
+import { withRouter } from 'react-router-dom';
+import './Login.scss';
+
+
+class LoginJaeyoung extends React.Component {
+ constructor () {
+ super();
+ this.state = {
+ id: '',
+ pw : '',
+ };
+ }
+
+ handleInput = (e) => {
+ const { name,value} = e.target;
+ this.setState({
+ [name]: value
+ })
+ }
+
+ goToMain = () => {
+ this.props.history.push('/main-jaeyoung')
+ }
+
+
+ render () {
+ const { handleInput } = this
+ const isBtnAble = this.state.id.includes('@') && this.state.pw.length >= 5;
+
+
+ return (
+ <div className="loginContainer">
+ <div className="logoName">
+ <h1>Instargram</h1>
+ </div>
+ <div className="loginInfo">
+ <input type="text" name="id" onChange={handleInput} className="loginId" placeholder="전화번호, 사용자 이름 또는 이메일" />
+ <input type="password" name="pw" onChange={handleInput} className="loginPs" placeholder="비밀번호"/>
+ <button className="loginBt" onClick={this.goToMain} disabled={!isBtnAble}>로그인</button>
+ </div>
+ <div className="forgetPassword">
+ <a href="https://www.naver.com/">비밀번호를 잊으셨나요?</a>
+ </div>
+ </div>
+ )
+ }
+}
+
+export default withRouter( LoginJaeyoung );
\ No newline at end of file | JavaScript | 수정했습니다! |
@@ -0,0 +1,50 @@
+import React from 'react';
+import { withRouter } from 'react-router-dom';
+import './Login.scss';
+
+
+class LoginJaeyoung extends React.Component {
+ constructor () {
+ super();
+ this.state = {
+ id: '',
+ pw : '',
+ };
+ }
+
+ handleInput = (e) => {
+ const { name,value} = e.target;
+ this.setState({
+ [name]: value
+ })
+ }
+
+ goToMain = () => {
+ this.props.history.push('/main-jaeyoung')
+ }
+
+
+ render () {
+ const { handleInput } = this
+ const isBtnAble = this.state.id.includes('@') && this.state.pw.length >= 5;
+
+
+ return (
+ <div className="loginContainer">
+ <div className="logoName">
+ <h1>Instargram</h1>
+ </div>
+ <div className="loginInfo">
+ <input type="text" name="id" onChange={handleInput} className="loginId" placeholder="전화번호, 사용자 이름 또는 이메일" />
+ <input type="password" name="pw" onChange={handleInput} className="loginPs" placeholder="비밀번호"/>
+ <button className="loginBt" onClick={this.goToMain} disabled={!isBtnAble}>로그인</button>
+ </div>
+ <div className="forgetPassword">
+ <a href="https://www.naver.com/">비밀번호를 잊으셨나요?</a>
+ </div>
+ </div>
+ )
+ }
+}
+
+export default withRouter( LoginJaeyoung );
\ No newline at end of file | JavaScript | 와...수정했습니다! |
@@ -0,0 +1,85 @@
+* {
+ box-sizing: border-box;
+}
+
+.loginContainer {
+ border: 2px solid #e6e6e6;
+ width: 350px;
+ height: 380px;
+ margin: 0 auto;
+ .logoName {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 100%;
+ h1 {
+ font-family: "Lobster", cursive;
+ width: 175px;
+ height: 52px;
+ text-align: center;
+ padding-top: 6px;
+ }
+ }
+ .loginInfo {
+ height: 213px;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ padding-top: 10px;
+ .loginId {
+ width: 268px;
+ height: 38px;
+ margin-bottom: 5px;
+ padding-left: 10px;
+ border-radius: 3px;
+ border: 1px solid #efefef;
+ background: #fafafa;
+ color: #9c9c9c;
+ font-size: 14px;
+ &:focus {
+ outline-color: gray;
+ }
+ }
+ .loginPs {
+ width: 268px;
+ height: 38px;
+ margin-bottom: 5px;
+ padding-left: 10px;
+ border-radius: 3px;
+ border: 1px solid #efefef;
+ background: #fafafa;
+ color: #9c9c9c;
+ font-size: 14px;
+ &:focus {
+ outline-color: gray;
+ }
+ }
+ .loginBt {
+ width: 268px;
+ height: 30px;
+ margin-top: 5px;
+ border-radius: 3px;
+ background-color: #2795f6;
+ color: #ffffff;
+ border-style: none;
+
+ &:focus {
+ outline: none;
+ }
+
+ &:disabled {
+ background-color: #b2dffc;
+ }
+ }
+ }
+ .forgetPassword{
+ display: flex;
+ justify-content: center;
+ margin-top: 20px;
+ a {
+ color: #043569; text-decoration: none;
+ }
+ }
+
+
+} | Unknown | 수정했습니다! 감사합니당 |
@@ -0,0 +1,190 @@
+import React from 'react';
+import FeedComponent from './FeedComponent/FeedComponent';
+import './Main.scss';
+import explore from '../../../images/jaeyoungLee/Main/explore.jpg';
+import heart from '../../../images/jaeyoungLee/Main/heart.jpg';
+import profile from '../../../images/jaeyoungLee/Main/profile.jpg';
+import heungminSon from '../../../images/jaeyoungLee/Main/손흥민.jpg';
+class MainJaeyoung extends React.Component {
+ constructor () {
+ super();
+ this.state = {
+ commentFeed : [],
+ }
+ }
+
+ componentDidMount() {
+ fetch('http://localhost:3000/data/feedData.json', {
+ method: 'GET'
+ })
+ .then(res => res.json())
+ .then(data => {
+ this.setState({
+ commentFeed: data,
+ });
+ });
+ }
+
+
+
+ render(){
+ const { commentFeed } = this.state;
+ return(
+ <>
+ <nav>
+ <div className="navcontents">
+ <div className="navleft">
+ <div className="navleftcontents">
+ <span className="logo"><i className="fab fa-instagram"></i></span>
+ <h1 className="logoname">westagram</h1>
+ </div>
+ </div>
+ <div className="navcenter">
+ <div className="navcentercontents">
+ <input className="search" type="text" placeholder="검색"/>
+ <span className="searchimg"><i className="fas fa-search"></i></span>
+ </div>
+ </div>
+ <div className="navright">
+ <div className="navrightcontents">
+ <img className="navexplore" src={explore} alt="탐험"/>
+ <img className="navheart" src={heart} alt="하트"/>
+ <img className="navprofile" src={profile} alt="프로필"/>
+ </div>
+ </div>
+ </div>
+ </nav>
+ <div className="main">
+ <div className="feeds">
+ <div className="story">
+ <div className="storyimgbox">
+ <div className="storycontents">
+ <div className="storyprofile">
+ <div className="storylastbox">
+ <div className="storylast">
+ <img className="storyimg1" src={heungminSon} alt="프로필1"/>
+ <p className="storyp1">손흥민</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://instagram.famm6-1.fna.fbcdn.net/v/t51.2885-19/44884218_345707102882519_2446069589734326272_n.jpg?_nc_ht=instagram.famm6-1.fna.fbcdn.net&_nc_ohc=mhDR9_0DpXIAX_KX0iq&ccb=7-4&oh=dcbb150241d6b1336dd54a4a20417b2a&oe=608B680F&_nc_sid=712cc3&ig_cache_key=YW5vbnltb3VzX3Byb2ZpbGVfcGlj.2-ccb7-4" alt="프로필1"/>
+ <p className="storyp1">2wo0</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/35999304_258159611658935_7092278198804676608_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=et4sZhNbgpAAX-qKBH9&ccb=7-4&oh=0b254f6fb3e4182513c3e20ed1a326d0&oe=608BC5C1&_nc_sid=48a2a6" alt="프로필1"/>
+ <p className="storyp1">geg</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/150675895_144233967522798_7515094658452540248_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=xslO4Za0644AX9cwObZ&ccb=7-4&oh=0f5cb82fd80b51b47d74e160e228aa1c&oe=608D7B5E&_nc_sid=48a2a6" alt="프로필1"/>
+ <p className="storyp1">h._.j</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/135771971_1881013862054625_6713353513169410837_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=SxJIiqRh4rcAX8RSLYk&ccb=7-4&oh=6dec08c37a69cb2c2a14f21bc36b5eef&oe=608C0912&_nc_sid=48a2a6" alt="프로필1"/>
+ <p className="storyp1">idon</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/155951500_335125831259326_3729086392261698560_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=3nnTQdlVU98AX_4fVMv&ccb=7-4&oh=4a596fc0e33f2ece37634ae50d38cdde&oe=608C5901&_nc_sid=48a2a6" alt="프로필1"/>
+ <p className="storyp1">dfewg</p>
+ </div>
+ <div className="storylast">
+ <img className="storyimg1" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/37828240_293117218102022_6759937585105076224_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=jzs6QvrGtHAAX_qFR80&ccb=7-4&oh=f4984cbce61bc445f02622a5468278b3&oe=608B09A1&_nc_sid=57d425" alt="프로필1"/>
+ <p className="storyp1">33gg</p>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ {commentFeed.map((feed,id) =>{
+ return (
+ <FeedComponent key={feed.id} profileimg={feed.profileimg} userName={feed.userName} feedimg={feed.feedimg} feedcontent={feed.feedcontent} />
+ );
+ })}
+
+ </div>
+ <div className="main-right">
+ <div className="my_profile">
+ <img className="my_profileimg" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/141997127_1523884024669097_6148385093252095280_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=ldPmBqcpW3kAX9esSCC&ccb=7-4&oh=6503a99b1b0096ad362012fef7e72aed&oe=6085537E&_nc_sid=7b02f1" alt="프로필"/>
+ <div className="my_info">
+ <p className="mynickname">2wo0_0</p>
+ <p className="myname">이재영</p>
+ </div>
+ <button className="profile_transform" disabled>전환</button>
+ </div>
+ <div className="recommendation">
+ <div className="recommendation_header">
+ <p className="recommendation_left">회원님을 위한 추천</p>
+ <p className="recommendation_right">모두 보기</p>
+ </div>
+ <div className="recommendation_info">
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/156650140_116853317083347_8770042214751161261_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=-evbCZABANYAX_WcDzP&edm=AEF8tYYAAAAA&ccb=7-4&oh=5eb6e52a64b2ad8c98bff45dab473831&oe=60880D5B&_nc_sid=a9513d" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">ryu_d_g</p>
+ <p className="other_friend">1996yunsi님 외 13명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/159992110_105322351555148_1839915921172216453_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=xfLIvYCwwiIAX8AJI08&ccb=7-4&oh=7bdaf0e022e88f0dd5079c1995892031&oe=608D9B9E&_nc_sid=57d425" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">2s2_f</p>
+ <p className="other_friend">_sihyeon___님 외 49명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/160716680_272942871038831_8108440433038115559_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=VmeF5WmeLg4AX-jiUAL&ccb=7-4&oh=cf29d0253e8afb755a9d26ad13a6deda&oe=608D4A0C&_nc_sid=a9513d" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">rdfe_g</p>
+ <p className="other_friend">111_fkdn님 외 5명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src="https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/164274433_776408706413539_3215024154205561736_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=gCCfowKp9OMAX9_NBIP&ccb=7-4&oh=afbada353869184275b4d3be70f38605&oe=608BE909&_nc_sid=a9513d" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">cat_2d_g</p>
+ <p className="other_friend">cjdtkseh님 외 15명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ <div className="recommendation_box">
+ <img className="friend_profile" src=" https://scontent-ssn1-1.cdninstagram.com/v/t51.2885-19/s150x150/164520013_834814623778500_398528442563386719_n.jpg?tp=1&_nc_ht=scontent-ssn1-1.cdninstagram.com&_nc_ohc=iLm66uEJKQ4AX88GkVl&ccb=7-4&oh=4fe271ebb6f627b328cb3d24bb811776&oe=608E6098&_nc_sid=86f79a" alt="다른프로필"/>
+ <div className="friend_info">
+ <p className="friend_nickname">tksdkdnENr</p>
+ <p className="other_friend">cjfcjfgme1님 외 32명이 팔로우합니다</p>
+ </div>
+ <button className="follow" disabled>팔로우</button>
+ </div>
+ </div>
+ </div>
+ <aside>
+ <ul className="westagram_contents_box">
+ {CONTENTS.map((el,id) =>
+ <li key={id} className="westagram_contents">{el.content}</li>
+ )}
+
+ </ul>
+ <p className="westagram_facebook">© 2021 INSTAGRAM FROM FACEBOOK</p>
+ </aside>
+ </div>
+ </div>
+ </>
+ )
+ }
+}
+export default MainJaeyoung ;
+
+const CONTENTS = [
+ {id: 1, content: "소개"},
+ {id: 2, content: "도움말"},
+ {id: 3, content: "홍보 센터"},
+ {id: 4, content: "API"},
+ {id: 5, content: "채용정보"},
+ {id: 6, content: "개인정보처리방침"},
+ {id: 7, content: "약관"},
+ {id: 8, content: "위치"},
+ {id: 9, content: "인기 계정"},
+ {id: 10, content: "해시태그"},
+ {id: 11, content: "언어"},
+]
\ No newline at end of file | JavaScript | 수정했습니다! 감사합니다! |
@@ -5,13 +5,15 @@
import com.somemore.domains.review.dto.response.ReviewDetailResponseDto;
import com.somemore.domains.review.dto.response.ReviewDetailWithNicknameResponseDto;
import com.somemore.domains.review.usecase.ReviewQueryUseCase;
+import com.somemore.global.auth.annotation.RoleId;
import com.somemore.global.common.response.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
+import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -41,7 +43,7 @@ public ApiResponse<ReviewDetailResponseDto> getById(@PathVariable Long id) {
);
}
- @Operation(summary = "기관별 리뷰 조회", description = "기관 ID를 사용하여 리뷰 조회")
+ @Operation(summary = "특정 기관 리뷰 조회", description = "기관 ID를 사용하여 리뷰 조회")
@GetMapping("/reviews/center/{centerId}")
public ApiResponse<Page<ReviewDetailWithNicknameResponseDto>> getReviewsByCenterId(
@PathVariable UUID centerId,
@@ -53,14 +55,34 @@ public ApiResponse<Page<ReviewDetailWithNicknameResponseDto>> getReviewsByCenter
.pageable(pageable)
.build();
+ return ApiResponse.ok(
+ 200,
+ reviewQueryUseCase.getDetailsWithNicknameByCenterId(centerId, condition),
+ "특정 기관 리뷰 리스트 조회 성공"
+ );
+ }
+
+ @Secured("ROLE_CENTER")
+ @Operation(summary = "기관 리뷰 조회", description = "기관 자신의 리뷰 조회")
+ @GetMapping("/reviews/center/me")
+ public ApiResponse<Page<ReviewDetailWithNicknameResponseDto>> getMyCenterReviews(
+ @RoleId UUID centerId,
+ @PageableDefault(sort = "created_at", direction = DESC) Pageable pageable,
+ @RequestParam(required = false) VolunteerCategory category
+ ) {
+ ReviewSearchCondition condition = ReviewSearchCondition.builder()
+ .category(category)
+ .pageable(pageable)
+ .build();
+
return ApiResponse.ok(
200,
reviewQueryUseCase.getDetailsWithNicknameByCenterId(centerId, condition),
"기관 리뷰 리스트 조회 성공"
);
}
- @Operation(summary = "봉사자 리뷰 조회", description = "봉사자 ID를 사용하여 리뷰 조회")
+ @Operation(summary = "특정 봉사자 리뷰 조회", description = "봉사자 ID를 사용하여 리뷰 조회")
@GetMapping("/reviews/volunteer/{volunteerId}")
public ApiResponse<Page<ReviewDetailWithNicknameResponseDto>> getReviewsByVolunteerId(
@PathVariable UUID volunteerId,
@@ -75,7 +97,27 @@ public ApiResponse<Page<ReviewDetailWithNicknameResponseDto>> getReviewsByVolunt
return ApiResponse.ok(
200,
reviewQueryUseCase.getDetailsWithNicknameByVolunteerId(volunteerId, condition),
- "유저 리뷰 리스트 조회 성공"
+ "특정 봉사자 리뷰 리스트 조회 성공"
+ );
+ }
+
+ @Secured("ROLE_VOLUNTEER")
+ @Operation(summary = "봉사자 리뷰 조회", description = "봉사자 자신의 리뷰 조회")
+ @GetMapping("/reviews/volunteer/me")
+ public ApiResponse<Page<ReviewDetailWithNicknameResponseDto>> getMyVolunteerReviews(
+ @RoleId UUID volunteerId,
+ @PageableDefault(sort = "created_at", direction = DESC) Pageable pageable,
+ @RequestParam(required = false) VolunteerCategory category
+ ) {
+ ReviewSearchCondition condition = ReviewSearchCondition.builder()
+ .category(category)
+ .pageable(pageable)
+ .build();
+
+ return ApiResponse.ok(
+ 200,
+ reviewQueryUseCase.getDetailsWithNicknameByVolunteerId(volunteerId, condition),
+ "봉사자 리뷰 리스트 조회 성공"
);
}
| Java | 빌더 로직을 컨디션 클래스의 of 정적 메서드에서 진행하면 더 깔끔할 것 같아요~
굳이 수정할 필요는 없다고 생각합니다! |
@@ -1,35 +1,34 @@
package com.somemore.domains.review.service;
-import com.somemore.domains.center.usecase.query.CenterQueryUseCase;
+import static com.somemore.global.exception.ExceptionMessage.NOT_EXISTS_REVIEW;
+
import com.somemore.domains.review.domain.Review;
import com.somemore.domains.review.dto.condition.ReviewSearchCondition;
import com.somemore.domains.review.dto.response.ReviewDetailResponseDto;
import com.somemore.domains.review.dto.response.ReviewDetailWithNicknameResponseDto;
import com.somemore.domains.review.repository.ReviewRepository;
import com.somemore.domains.review.usecase.ReviewQueryUseCase;
-import com.somemore.domains.volunteer.domain.Volunteer;
-import com.somemore.domains.volunteer.usecase.VolunteerQueryUseCase;
+import com.somemore.domains.volunteerapply.usecase.VolunteerApplyQueryUseCase;
import com.somemore.global.exception.NoSuchElementException;
+import com.somemore.volunteer.repository.record.VolunteerNicknameAndId;
+import com.somemore.volunteer.usecase.NEWVolunteerQueryUseCase;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
-import static com.somemore.global.exception.ExceptionMessage.NOT_EXISTS_REVIEW;
-
@RequiredArgsConstructor
@Transactional(readOnly = true)
@Service
public class ReviewQueryService implements ReviewQueryUseCase {
private final ReviewRepository reviewRepository;
- private final VolunteerQueryUseCase volunteerQueryUseCase;
- private final CenterQueryUseCase centerQueryUseCase;
+ private final NEWVolunteerQueryUseCase volunteerQueryUseCase;
+ private final VolunteerApplyQueryUseCase volunteerApplyQueryUseCase;
@Override
public boolean existsByVolunteerApplyId(Long volunteerApplyId) {
@@ -45,7 +44,9 @@ public Review getById(Long id) {
@Override
public ReviewDetailResponseDto getDetailById(Long id) {
Review review = getById(id);
- return ReviewDetailResponseDto.from(review);
+ Long recruitBoardId = volunteerApplyQueryUseCase.getRecruitBoardIdById(
+ review.getVolunteerApplyId());
+ return ReviewDetailResponseDto.of(review, recruitBoardId);
}
@Override
@@ -54,10 +55,11 @@ public Page<ReviewDetailWithNicknameResponseDto> getDetailsWithNicknameByVolunte
ReviewSearchCondition condition
) {
String nickname = volunteerQueryUseCase.getNicknameById(volunteerId);
- Page<Review> reviews = reviewRepository.findAllByVolunteerIdAndSearch(volunteerId, condition);
+ Page<Review> reviews = reviewRepository.findAllByVolunteerIdAndSearch(volunteerId,
+ condition);
return reviews.map(
- review -> ReviewDetailWithNicknameResponseDto.from(review, nickname)
+ review -> ReviewDetailWithNicknameResponseDto.of(review, nickname)
);
}
@@ -66,28 +68,20 @@ public Page<ReviewDetailWithNicknameResponseDto> getDetailsWithNicknameByCenterI
UUID centerId,
ReviewSearchCondition condition
) {
- centerQueryUseCase.validateCenterExists(centerId);
-
Page<Review> reviews = reviewRepository.findAllByCenterIdAndSearch(centerId, condition);
List<UUID> volunteerIds = reviews.get().map(Review::getVolunteerId).toList();
- Map<UUID, String> volunteerNicknames = getVolunteerNicknames(volunteerIds);
+ Map<UUID, String> volunteerNicknames = mapVolunteerIdsToNicknames(volunteerIds);
- return reviews.map(
- review -> {
- String nickname = volunteerNicknames.getOrDefault(review.getVolunteerId(),
- "삭제된 아이디");
- return ReviewDetailWithNicknameResponseDto.from(review, nickname);
- });
+ return reviews.map(review ->
+ ReviewDetailWithNicknameResponseDto.of(review,
+ volunteerNicknames.get(review.getVolunteerId()))
+ );
}
- private Map<UUID, String> getVolunteerNicknames(List<UUID> volunteerIds) {
- List<Volunteer> volunteers = volunteerQueryUseCase.getAllByIds(volunteerIds);
-
- Map<UUID, String> volunteerNicknames = new HashMap<>();
- for (Volunteer volunteer : volunteers) {
- volunteerNicknames.put(volunteer.getId(), volunteer.getNickname());
- }
-
- return volunteerNicknames;
+ private Map<UUID, String> mapVolunteerIdsToNicknames(List<UUID> volunteerIds) {
+ return volunteerQueryUseCase.getVolunteerNicknameAndIdsByIds(volunteerIds)
+ .stream()
+ .collect(Collectors.toMap(VolunteerNicknameAndId::id,
+ VolunteerNicknameAndId::nickname));
}
} | Java | 메서드로 코드를 포장하면 가독성이 더 좋을 것 같아요~ |
@@ -1,35 +1,34 @@
package com.somemore.domains.review.service;
-import com.somemore.domains.center.usecase.query.CenterQueryUseCase;
+import static com.somemore.global.exception.ExceptionMessage.NOT_EXISTS_REVIEW;
+
import com.somemore.domains.review.domain.Review;
import com.somemore.domains.review.dto.condition.ReviewSearchCondition;
import com.somemore.domains.review.dto.response.ReviewDetailResponseDto;
import com.somemore.domains.review.dto.response.ReviewDetailWithNicknameResponseDto;
import com.somemore.domains.review.repository.ReviewRepository;
import com.somemore.domains.review.usecase.ReviewQueryUseCase;
-import com.somemore.domains.volunteer.domain.Volunteer;
-import com.somemore.domains.volunteer.usecase.VolunteerQueryUseCase;
+import com.somemore.domains.volunteerapply.usecase.VolunteerApplyQueryUseCase;
import com.somemore.global.exception.NoSuchElementException;
+import com.somemore.volunteer.repository.record.VolunteerNicknameAndId;
+import com.somemore.volunteer.usecase.NEWVolunteerQueryUseCase;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
-import static com.somemore.global.exception.ExceptionMessage.NOT_EXISTS_REVIEW;
-
@RequiredArgsConstructor
@Transactional(readOnly = true)
@Service
public class ReviewQueryService implements ReviewQueryUseCase {
private final ReviewRepository reviewRepository;
- private final VolunteerQueryUseCase volunteerQueryUseCase;
- private final CenterQueryUseCase centerQueryUseCase;
+ private final NEWVolunteerQueryUseCase volunteerQueryUseCase;
+ private final VolunteerApplyQueryUseCase volunteerApplyQueryUseCase;
@Override
public boolean existsByVolunteerApplyId(Long volunteerApplyId) {
@@ -45,7 +44,9 @@ public Review getById(Long id) {
@Override
public ReviewDetailResponseDto getDetailById(Long id) {
Review review = getById(id);
- return ReviewDetailResponseDto.from(review);
+ Long recruitBoardId = volunteerApplyQueryUseCase.getRecruitBoardIdById(
+ review.getVolunteerApplyId());
+ return ReviewDetailResponseDto.of(review, recruitBoardId);
}
@Override
@@ -54,10 +55,11 @@ public Page<ReviewDetailWithNicknameResponseDto> getDetailsWithNicknameByVolunte
ReviewSearchCondition condition
) {
String nickname = volunteerQueryUseCase.getNicknameById(volunteerId);
- Page<Review> reviews = reviewRepository.findAllByVolunteerIdAndSearch(volunteerId, condition);
+ Page<Review> reviews = reviewRepository.findAllByVolunteerIdAndSearch(volunteerId,
+ condition);
return reviews.map(
- review -> ReviewDetailWithNicknameResponseDto.from(review, nickname)
+ review -> ReviewDetailWithNicknameResponseDto.of(review, nickname)
);
}
@@ -66,28 +68,20 @@ public Page<ReviewDetailWithNicknameResponseDto> getDetailsWithNicknameByCenterI
UUID centerId,
ReviewSearchCondition condition
) {
- centerQueryUseCase.validateCenterExists(centerId);
-
Page<Review> reviews = reviewRepository.findAllByCenterIdAndSearch(centerId, condition);
List<UUID> volunteerIds = reviews.get().map(Review::getVolunteerId).toList();
- Map<UUID, String> volunteerNicknames = getVolunteerNicknames(volunteerIds);
+ Map<UUID, String> volunteerNicknames = mapVolunteerIdsToNicknames(volunteerIds);
- return reviews.map(
- review -> {
- String nickname = volunteerNicknames.getOrDefault(review.getVolunteerId(),
- "삭제된 아이디");
- return ReviewDetailWithNicknameResponseDto.from(review, nickname);
- });
+ return reviews.map(review ->
+ ReviewDetailWithNicknameResponseDto.of(review,
+ volunteerNicknames.get(review.getVolunteerId()))
+ );
}
- private Map<UUID, String> getVolunteerNicknames(List<UUID> volunteerIds) {
- List<Volunteer> volunteers = volunteerQueryUseCase.getAllByIds(volunteerIds);
-
- Map<UUID, String> volunteerNicknames = new HashMap<>();
- for (Volunteer volunteer : volunteers) {
- volunteerNicknames.put(volunteer.getId(), volunteer.getNickname());
- }
-
- return volunteerNicknames;
+ private Map<UUID, String> mapVolunteerIdsToNicknames(List<UUID> volunteerIds) {
+ return volunteerQueryUseCase.getVolunteerNicknameAndIdsByIds(volunteerIds)
+ .stream()
+ .collect(Collectors.toMap(VolunteerNicknameAndId::id,
+ VolunteerNicknameAndId::nickname));
}
} | Java | 복수형 정적 팩토리 메서드 |
@@ -0,0 +1,21 @@
+import { EOL as LINE_SEPARATOR } from 'os';
+import { TIME, UNITS } from './system.js';
+
+export const OUTPUT_MESSAGES = Object.freeze({
+ intro: `안녕하세요! 우테코 식당 ${TIME.month}${UNITS.month} 이벤트 플래너입니다.`,
+ outro: `일에 우테코 식당에서 받을 이벤트 혜택 미리 보기!`,
+});
+
+export const INPUT_MESSAGES = Object.freeze({
+ date: `${TIME.month}${UNITS.month} 중 식당 예상 방문 날짜는 언제인가요? (숫자만 입력해 주세요!)${LINE_SEPARATOR}`,
+ order: `주문하실 메뉴를 메뉴와 개수를 알려 주세요. (e.g. 해산물파스타-2,레드와인-1,초코케이크-1)${LINE_SEPARATOR}`,
+});
+
+export const ERROR_MESSAGES = Object.freeze({
+ prefix: '[ERROR]',
+ invalidDate: '유효하지 않은 날짜입니다. 다시 입력해 주세요.',
+ invalidMenu: '유효하지 않은 주문입니다. 다시 입력해 주세요.',
+ exceedQuantity:
+ '메뉴는 한 번에 최대 20개까지만 주문할 수 있습니다. 다시 입력해 주세요.',
+ onlyBeverage: '음료만 주문할 수 없습니다. 다시 입력해 주세요.',
+}); | JavaScript | 이벤트를 진행하는 달이 바뀌는 것을 고려해 `TIME.month` 상수를 따로 생성한 점이 인상 깊어요!
`12월 이벤트 참여 고객의 5%가 내년 1월 새해 이벤트에 재참여하는 것`
이메일의 이러한 문장이 저도 눈에 밟히긴 했는데 그냥 기능 구현에 집중하느라 잊어버렸거든요..
정말 섬세하게 고민하시면서 구현하신 것 같습니다! 감탄만 나오네요 😮 |
@@ -0,0 +1,28 @@
+export const TIME = Object.freeze({
+ year: '2023',
+ month: '12',
+ dateFormat: `2023-12-`,
+});
+
+export const PROMOTION_TITLES = Object.freeze({
+ 1: '새해',
+ 12: '크리스마스',
+});
+
+export const SYMBOLS = Object.freeze({
+ comma: ',',
+ dash: '-',
+ colon: ':',
+ blank: '',
+});
+
+export const UNITS = Object.freeze({
+ quantity: '개',
+ won: '원',
+ month: '월',
+ year: '년',
+});
+
+export const NONE = '없음';
+
+export const FILE_PATH = 'src/data/dec-promotion.json'; | JavaScript | 확장을 고려하셨군요! 배우고 갑니다 👍
실제 회사였다면 이벤트 기획자가 너무 좋아할 것 같아요! |
@@ -0,0 +1,28 @@
+export const TIME = Object.freeze({
+ year: '2023',
+ month: '12',
+ dateFormat: `2023-12-`,
+});
+
+export const PROMOTION_TITLES = Object.freeze({
+ 1: '새해',
+ 12: '크리스마스',
+});
+
+export const SYMBOLS = Object.freeze({
+ comma: ',',
+ dash: '-',
+ colon: ':',
+ blank: '',
+});
+
+export const UNITS = Object.freeze({
+ quantity: '개',
+ won: '원',
+ month: '월',
+ year: '년',
+});
+
+export const NONE = '없음';
+
+export const FILE_PATH = 'src/data/dec-promotion.json'; | JavaScript | 그냥 감탄만 나오네요... 할말이 없네요... 최종 코테 이런분이 가시는구나... |
@@ -0,0 +1,87 @@
+import VisitDate from '../domain/VisitDate.js';
+import Order from '../domain/Order.js';
+import InputView from '../views/InputView.js';
+import OutputView from '../views/OutputView.js';
+import EventPlanner from '../domain/EventPlanner.js';
+import Save from '../domain/Save.js';
+
+class EventController {
+ #inputView;
+
+ #outputView;
+
+ #dayIndex;
+
+ #eventPlanner;
+
+ constructor() {
+ this.#inputView = InputView;
+ this.#outputView = OutputView;
+ }
+
+ async startEvent() {
+ this.#outputView.printIntro();
+
+ const visitDate = await this.#requestVisitDate();
+ const orderList = await this.#requestOrderList();
+
+ this.#eventPlanner = this.#showEventPlanner(visitDate, orderList);
+ this.#saveResult(this.#eventPlanner);
+ }
+
+ /**
+ * 방문 날짜를 입력 받아 반환, 요일 인덱스 멤버 변수 할당
+ * @returns {number} - 요일 인덱스
+ */
+ async #requestVisitDate() {
+ try {
+ const visitDate = await this.#inputView.readDate();
+ this.#dayIndex = new VisitDate(visitDate).getDayIndex();
+
+ return visitDate;
+ } catch ({ message }) {
+ this.#outputView.print(message);
+
+ return this.#requestVisitDate();
+ }
+ }
+
+ /**
+ * 주문할 메뉴와 개수를 입력 받아 가공한 주문 메뉴를 리턴
+ * @returns {Set<{ menu: string, quantity: number }>}
+ */
+ async #requestOrderList() {
+ try {
+ const orderInput = await this.#inputView.readOrder();
+
+ return new Order(orderInput).getOrderList();
+ } catch ({ message }) {
+ this.#outputView.print(message);
+
+ return this.#requestOrderList();
+ }
+ }
+
+ /**
+ * 유저의 입력 값을 기반으로 이벤트 플래너를 구성하고 출력
+ * @param {number} visitDate - 요일 인덱스
+ * @param {Set<{ menu: string, quantity: number }>} orderList - 주문 메뉴와 수량을 나타내는 Set 객체
+ * @returns
+ */
+ #showEventPlanner(visitDate, orderList) {
+ this.#outputView.printOutro(visitDate);
+ this.#eventPlanner = new EventPlanner(visitDate, this.#dayIndex, orderList);
+ this.#outputView.printPlanner(orderList, this.#eventPlanner);
+
+ return this.#eventPlanner;
+ }
+
+ /**
+ * 이벤트 플래너의 주요 데이터를 Save 클래스에 넘겨 저장
+ */
+ #saveResult() {
+ new Save(this.#eventPlanner);
+ }
+}
+
+export default EventController; | JavaScript | 에러메시지 출력 기능을 `outputView`가 책임을 맡도록 했군요! 리팩토링 할 때 저도 반영해봐야겠습니다 👍 |
@@ -0,0 +1,32 @@
+import { ERROR_MESSAGES } from '../constants/messages.js';
+import { TIME } from '../constants/system.js';
+import validationErrorHandler from '../errors/index.js';
+import { isPositiveInteger, isValidDate } from '../validators/index.js';
+
+class VisitDate {
+ #visitDate;
+
+ constructor(date) {
+ this.#validateDate(date);
+ this.#visitDate = date;
+ }
+
+ #validateDate(date) {
+ if (!isPositiveInteger(date) || !isValidDate(date)) {
+ validationErrorHandler(ERROR_MESSAGES.invalidDate);
+ }
+ }
+
+ getDayIndex() {
+ return this.#calculateDayIndex();
+ }
+
+ // 이벤트 연-월의 방문 날짜를 계산하여 요일 인덱스를 반환
+ #calculateDayIndex() {
+ const date = new Date(`${TIME.dateFormat}${this.#visitDate}`);
+
+ return date.getDay();
+ }
+}
+
+export default VisitDate; | JavaScript | 기본 제공되는 `Date` 객체를 활용할 생각은 못했네요!
이렇게 신박한 방법도 있다는 것을 알아갑니다 👍 |
@@ -0,0 +1,9 @@
+import { ERROR_MESSAGES } from '../constants/messages.js';
+
+class AppError extends Error {
+ constructor(message) {
+ super(`${ERROR_MESSAGES.prefix} ${message}`);
+ }
+}
+
+export default AppError; | JavaScript | 에러를 상속하셨군요! 정말 체계적인 코드인 것 같아요!
`Error`를 상속해 `AppError` 클래스를 따로 만드시게 된 계기를 여쭤봐도 될까요? |
@@ -0,0 +1,12 @@
+import MENUS from '../constants/menus.js';
+
+/**
+ * 메뉴 이름을 입력하면 카테고리 내 메뉴의 가격 값을 반환
+ * @param {string} menu - 메뉴 이름
+ * @returns {number | undefined}
+ */
+const menuPriceFinder = menu => {
+ return Object.values(MENUS).find(category => menu in category)[menu];
+};
+
+export default menuPriceFinder; | JavaScript | 기능을 구현하다보면 메뉴의 가격을 자주 가져다 쓰게 되는데 utils 폴더에 따로 함수를 구현해두니 좋은 것 같아요!
배워갑니다 👏 |
@@ -0,0 +1,15 @@
+import { UNITS } from '../constants/system.js';
+
+/**
+ * number type의 가격을 입력받아 가격을 변환 후 '원'을 포함한 string type으로 변환
+ * 20000이라는 매개변수를 통해 '20,000원'을 반환
+ * @param {number} price 가격
+ * @returns {string}
+ */
+const priceFormatter = price => {
+ const formattedPrice = new Intl.NumberFormat().format(price);
+
+ return `${formattedPrice}${UNITS.won}`;
+};
+
+export default priceFormatter; | JavaScript | `Intl.NumberFormat` 를 처음 접했는데 이렇게 가격을 포맷하는 간단한 방법이 있었군요!
저는 정규표현식으로 구현했는데 새로운 방법을 알아가게 돼서 좋아요! |
@@ -0,0 +1,68 @@
+import { ERROR_MESSAGES } from '../constants/messages.js';
+import { SYMBOLS } from '../constants/system.js';
+import validationErrorHandler from '../errors/index.js';
+import { isValidMenuName } from '../validators/index.js';
+import { isOnlyBeverage } from '../validators/is-valid-menu/name.js';
+import {
+ isValidEachMenuQuantity,
+ isValidTotalMenuQuantity,
+} from '../validators/is-valid-menu/quantity.js';
+
+class Order {
+ #orderList = new Set();
+
+ constructor(orderInput) {
+ this.#validate(orderInput);
+ this.#orderList = this.#parse(orderInput);
+ }
+
+ /**
+ * 사용자 입력한 주문 메뉴와 메뉴 개수를 파싱하여 배열로 반환
+ * @param {string} orderInput - 사용자가 입력한 모든 주문 메뉴와 메뉴 개수
+ * @returns {{ key: string, value: string }[]} - 주문이 파싱된 배열
+ */
+ #parse(orderInput) {
+ this.#splitOrder(orderInput);
+
+ return [...this.#orderList];
+ }
+
+ /**
+ * orderInput 내 개별 주문들을 파싱
+ * @param {string} orderInput - 사용자가 입력한 모든 주문 메뉴와 메뉴 개수
+ * @returns {Set<{ menu: string, quantity: number }>} - 주문이 파싱된 Set
+ */
+ #splitOrder(orderInput) {
+ return orderInput.split(SYMBOLS.comma).map(order => this.#splitMenu(order));
+ }
+
+ /**
+ * 주문 메뉴명과 개수를 orderList Set에 추가
+ * @param {string} order 사용자가 입력한 특정 주문 메뉴와 메뉴 개수
+ */
+ #splitMenu(order) {
+ const [menu, quantity] = order.split(SYMBOLS.dash);
+
+ this.#orderList.add({ menu: menu.trim(), quantity: Number(quantity) });
+ }
+
+ #validate(orderInput) {
+ if (!isValidMenuName(orderInput) || !isValidEachMenuQuantity(orderInput)) {
+ validationErrorHandler(ERROR_MESSAGES.invalidMenu);
+ }
+
+ if (!isValidTotalMenuQuantity(orderInput)) {
+ validationErrorHandler(ERROR_MESSAGES.exceedQuantity);
+ }
+
+ if (isOnlyBeverage(orderInput)) {
+ validationErrorHandler(ERROR_MESSAGES.onlyBeverage);
+ }
+ }
+
+ getOrderList() {
+ return this.#orderList;
+ }
+}
+
+export default Order; | JavaScript | 메소드 순서를 잘 정하셔서 이해하기 정말 좋았습니다!
어, 이 메소드는 뭐지? 싶으면 바로 밑에 그 메소드가 있어서 술술 읽혔어요!
메소드 순서도 컨벤션이라고 하는 공통 피드백이 있었는데 그걸 잘 반영하신 것 같아요 👍 |
@@ -0,0 +1,57 @@
+import { GIVEAWAYS, TITLES } from '../constants/events.js';
+import { NONE } from '../constants/system.js';
+import menuPriceFinder from '../utils/menuPriceFinder.js';
+
+class Benefit {
+ #isFitGiveaway;
+
+ #benefitList;
+
+ #totalPrice;
+
+ constructor(discountList, isFitGiveaway) {
+ this.#isFitGiveaway = isFitGiveaway;
+ this.#benefitList = this.#setBenefitList(discountList);
+ this.#totalPrice = this.#calculateTotalPrice();
+ }
+
+ /**
+ * 증정 이벤트 기준 이상이면 혜택 내역에 증정 메뉴를 추가하고, 미만이면 '없음'을 추가
+ * @param {Array<{ title: string, price: number }>} benefitList - 혜택 리스트
+ * @returns
+ */
+ #setBenefitList(discountList) {
+ if (this.#isFitGiveaway) {
+ return [...discountList, this.#createGiveawayBenefit()];
+ }
+
+ return discountList;
+ }
+
+ #createGiveawayBenefit() {
+ return {
+ title: TITLES.giveaway,
+ price: menuPriceFinder(GIVEAWAYS.giveaway),
+ };
+ }
+
+ /**
+ * 혜택 내역이 '없음'이면 총 금액 0을 반환, 혜택 내역이 있으면 총 금액을 누산하여 반환
+ * @returns
+ */
+ #calculateTotalPrice() {
+ if (this.#benefitList === NONE) return 0;
+
+ return this.#benefitList.reduce((acc, benefit) => acc + benefit.price, 0);
+ }
+
+ getList() {
+ return this.#benefitList;
+ }
+
+ getTotalPrice() {
+ return this.#totalPrice;
+ }
+}
+
+export default Benefit; | JavaScript | 3주차 공통 피드백에 `필드의 수를 줄이기 위해 노력한다`라는 말이 있었죠!
`#benefitList`와 `#totalPrice`는
생성자의 인수로 전달된 `discountList`, `isFitGiveaway`으로 만들 수 있기 때문에
꼭 필드로 선언해야 하는 건지에 대한 의문이 생깁니다!
필드의 개수를 최대한 줄이는 게 정말 옳은 것인지 고민이 많아지네요
희태님 생각은 어떠신가요?! |
@@ -0,0 +1,106 @@
+import { BADGES, GIVEAWAYS } from '../constants/events.js';
+import { NONE } from '../constants/system.js';
+import menuPriceFinder from '../utils/menuPriceFinder.js';
+import Benefit from './Benefit.js';
+import Discount from './Discount.js';
+
+class EventPlanner {
+ #benefit;
+
+ #preTotalPrice;
+
+ #totalBenefitPrice;
+
+ constructor(visitDate, dayIndex, orderList) {
+ this.discount = new Discount(visitDate, dayIndex, orderList);
+ this.#preTotalPrice = this.#setPreTotalPrice(orderList);
+ this.isFitGiveaway = this.#checkIsFitGiveAway();
+ this.#benefit = new Benefit(
+ this.discount.getDiscounts(this.#preTotalPrice),
+ this.isFitGiveaway,
+ );
+ }
+
+ /**
+ * 주문 내역을 순회하며 할인 전 총주문 금액을 반환
+ * @param {Array<{ menu: string, quantity: number }>} orderList - 주문 내역
+ * @returns
+ */
+ #setPreTotalPrice(orderList) {
+ return orderList.reduce(
+ (acc, order) => this.#calculateTotalPrice(acc, order),
+ 0,
+ );
+ }
+
+ /**
+ * 특정 메뉴의 가격과 수량을 곱하여 할인 전 총주문 금액을 계산
+ * @param {number} acc - 누적 금액
+ * @param {{ menu: string, quantity: number }} order - 특정 주문 내역
+ * @returns
+ */
+ #calculateTotalPrice(acc, order) {
+ const price = menuPriceFinder(order.menu);
+
+ return acc + price * order.quantity;
+ }
+
+ getPreTotalPrice() {
+ return this.#preTotalPrice;
+ }
+
+ // 할인 전 총주문 금액과 증정 이벤트 기준 금액을 비교하여 boolean 반환
+ #checkIsFitGiveAway() {
+ return this.#preTotalPrice >= GIVEAWAYS.giveawayPrice;
+ }
+
+ // 증정 이벤트 기준 금액 이상이면 증정 이벤트 상품 반환, 미만이면 '없음' 반환
+ getGiveaway() {
+ return this.isFitGiveaway ? [this.#createGiveaway()] : NONE;
+ }
+
+ #createGiveaway() {
+ return { menu: GIVEAWAYS.giveaway, quantity: GIVEAWAYS.giveawayUnit };
+ }
+
+ getBenefitList() {
+ const benefitList = this.#benefit.getList();
+
+ return benefitList.length ? benefitList : NONE;
+ }
+
+ getTotalBenefitPrice() {
+ this.#totalBenefitPrice = this.#benefit.getTotalPrice();
+
+ return this.#totalBenefitPrice;
+ }
+
+ /**
+ * 총 할인 금액이 존재하면 할인 후 예상 결제 금액 반환, 그렇지 않다면 할인 전 총주문 금액 반환
+ * @returns
+ */
+ getTotalPrice() {
+ const totalDiscountPrice = this.discount.getTotalDiscountPrice();
+
+ return this.#preTotalPrice - totalDiscountPrice;
+ }
+
+ /**
+ * 총혜택 금액에 따른 이벤트 배지 반환
+ * @returns
+ */
+ getBadge() {
+ switch (true) {
+ case this.#totalBenefitPrice > BADGES.santa.price:
+ return BADGES.santa.title;
+ case this.#totalBenefitPrice > BADGES.tree.price:
+ return BADGES.tree.title;
+ case this.#totalBenefitPrice > BADGES.star.price:
+ return BADGES.star.title;
+ default:
+ return NONE;
+ }
+ }
+}
+
+export default EventPlanner; | JavaScript | `switch`문을 사용하니 정말 깔끔한 것 같아요! |
@@ -0,0 +1,43 @@
+import fs from 'fs';
+import { FILE_PATH } from '../constants/system.js';
+
+class Save {
+ #eventPlanner;
+
+ #filePath;
+
+ constructor(eventPlanner) {
+ this.#eventPlanner = eventPlanner;
+ this.#filePath = FILE_PATH;
+ this.#writeData();
+ }
+
+ // 기존 JSON 데이터에 신규 데이터를 추가하고 저장
+ #writeData() {
+ const readData = this.#readData();
+ const userData = {
+ user: readData.length,
+ badge: this.#eventPlanner.getBadge(),
+ total: this.#eventPlanner.getPreTotalPrice(),
+ benefit: this.#eventPlanner.getTotalBenefitPrice(),
+ payment: this.#eventPlanner.getTotalPrice(),
+ };
+ readData.push(userData);
+ const jsonData = JSON.stringify(readData, null, 2);
+
+ fs.writeFileSync(this.#filePath, jsonData, 'utf-8');
+ }
+
+ // 데이터를 읽어와 파싱하여 반환, 기존의 데이터가 없다면 빈 배열 추가
+ #readData() {
+ try {
+ const data = fs.readFileSync(this.#filePath, 'utf-8');
+
+ return JSON.parse(data);
+ } catch (error) {
+ return [];
+ }
+ }
+}
+
+export default Save; | JavaScript | 방문한 손님들에 대한 데이터를 저장하는 기능은 생각 못 했는데
너무 좋은 아이디어입니다 ✨ |
@@ -0,0 +1,21 @@
+import { EOL as LINE_SEPARATOR } from 'os';
+import { TIME, UNITS } from './system.js';
+
+export const OUTPUT_MESSAGES = Object.freeze({
+ intro: `안녕하세요! 우테코 식당 ${TIME.month}${UNITS.month} 이벤트 플래너입니다.`,
+ outro: `일에 우테코 식당에서 받을 이벤트 혜택 미리 보기!`,
+});
+
+export const INPUT_MESSAGES = Object.freeze({
+ date: `${TIME.month}${UNITS.month} 중 식당 예상 방문 날짜는 언제인가요? (숫자만 입력해 주세요!)${LINE_SEPARATOR}`,
+ order: `주문하실 메뉴를 메뉴와 개수를 알려 주세요. (e.g. 해산물파스타-2,레드와인-1,초코케이크-1)${LINE_SEPARATOR}`,
+});
+
+export const ERROR_MESSAGES = Object.freeze({
+ prefix: '[ERROR]',
+ invalidDate: '유효하지 않은 날짜입니다. 다시 입력해 주세요.',
+ invalidMenu: '유효하지 않은 주문입니다. 다시 입력해 주세요.',
+ exceedQuantity:
+ '메뉴는 한 번에 최대 20개까지만 주문할 수 있습니다. 다시 입력해 주세요.',
+ onlyBeverage: '음료만 주문할 수 없습니다. 다시 입력해 주세요.',
+}); | JavaScript | 이번 미션에서는 확장성을 신경쓰고자 노력했는데 알아봐주셔서 감사할 따름입니다! 🙂 |
@@ -0,0 +1,32 @@
+import { ERROR_MESSAGES } from '../constants/messages.js';
+import { TIME } from '../constants/system.js';
+import validationErrorHandler from '../errors/index.js';
+import { isPositiveInteger, isValidDate } from '../validators/index.js';
+
+class VisitDate {
+ #visitDate;
+
+ constructor(date) {
+ this.#validateDate(date);
+ this.#visitDate = date;
+ }
+
+ #validateDate(date) {
+ if (!isPositiveInteger(date) || !isValidDate(date)) {
+ validationErrorHandler(ERROR_MESSAGES.invalidDate);
+ }
+ }
+
+ getDayIndex() {
+ return this.#calculateDayIndex();
+ }
+
+ // 이벤트 연-월의 방문 날짜를 계산하여 요일 인덱스를 반환
+ #calculateDayIndex() {
+ const date = new Date(`${TIME.dateFormat}${this.#visitDate}`);
+
+ return date.getDay();
+ }
+}
+
+export default VisitDate; | JavaScript | 아마 더 좋은 방법이 있을겁니다! :) 저도 `Date` 객체를 잘 활용하지 못한 것 같아서 더 공부해보려구요! |
@@ -0,0 +1,9 @@
+import { ERROR_MESSAGES } from '../constants/messages.js';
+
+class AppError extends Error {
+ constructor(message) {
+ super(`${ERROR_MESSAGES.prefix} ${message}`);
+ }
+}
+
+export default AppError; | JavaScript | 아무래도 `[ERROR]` 라는 prefix를 통해 에러 메시지를 정의하는 과정에서 만들게 되었는데요, 지정 에러 클래스를 사용하면 추후에 더 쉽게 확장할 수 있는 장점이 있지 않을까라는 생각이었습니다! |
@@ -0,0 +1,15 @@
+import { UNITS } from '../constants/system.js';
+
+/**
+ * number type의 가격을 입력받아 가격을 변환 후 '원'을 포함한 string type으로 변환
+ * 20000이라는 매개변수를 통해 '20,000원'을 반환
+ * @param {number} price 가격
+ * @returns {string}
+ */
+const priceFormatter = price => {
+ const formattedPrice = new Intl.NumberFormat().format(price);
+
+ return `${formattedPrice}${UNITS.won}`;
+};
+
+export default priceFormatter; | JavaScript | `Intl.NumberFormat` 생성자를 통해 다양한 통화 서식을 변환할 수 있더라구요!
[Intl.NumberFormat](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat)
도움이 될까싶어 링크 첨부해두었습니다 :) |
@@ -0,0 +1,57 @@
+import { GIVEAWAYS, TITLES } from '../constants/events.js';
+import { NONE } from '../constants/system.js';
+import menuPriceFinder from '../utils/menuPriceFinder.js';
+
+class Benefit {
+ #isFitGiveaway;
+
+ #benefitList;
+
+ #totalPrice;
+
+ constructor(discountList, isFitGiveaway) {
+ this.#isFitGiveaway = isFitGiveaway;
+ this.#benefitList = this.#setBenefitList(discountList);
+ this.#totalPrice = this.#calculateTotalPrice();
+ }
+
+ /**
+ * 증정 이벤트 기준 이상이면 혜택 내역에 증정 메뉴를 추가하고, 미만이면 '없음'을 추가
+ * @param {Array<{ title: string, price: number }>} benefitList - 혜택 리스트
+ * @returns
+ */
+ #setBenefitList(discountList) {
+ if (this.#isFitGiveaway) {
+ return [...discountList, this.#createGiveawayBenefit()];
+ }
+
+ return discountList;
+ }
+
+ #createGiveawayBenefit() {
+ return {
+ title: TITLES.giveaway,
+ price: menuPriceFinder(GIVEAWAYS.giveaway),
+ };
+ }
+
+ /**
+ * 혜택 내역이 '없음'이면 총 금액 0을 반환, 혜택 내역이 있으면 총 금액을 누산하여 반환
+ * @returns
+ */
+ #calculateTotalPrice() {
+ if (this.#benefitList === NONE) return 0;
+
+ return this.#benefitList.reduce((acc, benefit) => acc + benefit.price, 0);
+ }
+
+ getList() {
+ return this.#benefitList;
+ }
+
+ getTotalPrice() {
+ return this.#totalPrice;
+ }
+}
+
+export default Benefit; | JavaScript | 저는 우선 모든 메서드와 필드를 `private`으로 지정하고나서, 이후에 `public`으로 접근을 해야만 할때 `public`으로 전환하였습니다!
아마 이 과정에서도 클래스 내 메서드가 `benefitList`와 `totalPrice`를 사용함에 있어서 `public`으로 전환하지 않아도 될 것 같아서 그대로 두었습니다 :)
저도 사실 공통 피드백을 받고나서 필드의 개수를 최대한 줄여야하는 것과, 최대한 private 필드로 캡슐화를 구현하는 것 사이에서의 중간점을 못찾겠더라구요!
좋은 피드백 감사드립니다! `benefitList`와 `totalPrice`를 굳이 private 필드로 선언해야하는 근거가 없으면 줄이는것도 맞다고 생각이 듭니다. |
@@ -0,0 +1,68 @@
+import { ERROR_MESSAGES } from '../constants/messages.js';
+import { SYMBOLS } from '../constants/system.js';
+import validationErrorHandler from '../errors/index.js';
+import { isValidMenuName } from '../validators/index.js';
+import { isOnlyBeverage } from '../validators/is-valid-menu/name.js';
+import {
+ isValidEachMenuQuantity,
+ isValidTotalMenuQuantity,
+} from '../validators/is-valid-menu/quantity.js';
+
+class Order {
+ #orderList = new Set();
+
+ constructor(orderInput) {
+ this.#validate(orderInput);
+ this.#orderList = this.#parse(orderInput);
+ }
+
+ /**
+ * 사용자 입력한 주문 메뉴와 메뉴 개수를 파싱하여 배열로 반환
+ * @param {string} orderInput - 사용자가 입력한 모든 주문 메뉴와 메뉴 개수
+ * @returns {{ key: string, value: string }[]} - 주문이 파싱된 배열
+ */
+ #parse(orderInput) {
+ this.#splitOrder(orderInput);
+
+ return [...this.#orderList];
+ }
+
+ /**
+ * orderInput 내 개별 주문들을 파싱
+ * @param {string} orderInput - 사용자가 입력한 모든 주문 메뉴와 메뉴 개수
+ * @returns {Set<{ menu: string, quantity: number }>} - 주문이 파싱된 Set
+ */
+ #splitOrder(orderInput) {
+ return orderInput.split(SYMBOLS.comma).map(order => this.#splitMenu(order));
+ }
+
+ /**
+ * 주문 메뉴명과 개수를 orderList Set에 추가
+ * @param {string} order 사용자가 입력한 특정 주문 메뉴와 메뉴 개수
+ */
+ #splitMenu(order) {
+ const [menu, quantity] = order.split(SYMBOLS.dash);
+
+ this.#orderList.add({ menu: menu.trim(), quantity: Number(quantity) });
+ }
+
+ #validate(orderInput) {
+ if (!isValidMenuName(orderInput) || !isValidEachMenuQuantity(orderInput)) {
+ validationErrorHandler(ERROR_MESSAGES.invalidMenu);
+ }
+
+ if (!isValidTotalMenuQuantity(orderInput)) {
+ validationErrorHandler(ERROR_MESSAGES.exceedQuantity);
+ }
+
+ if (isOnlyBeverage(orderInput)) {
+ validationErrorHandler(ERROR_MESSAGES.onlyBeverage);
+ }
+ }
+
+ getOrderList() {
+ return this.#orderList;
+ }
+}
+
+export default Order; | JavaScript | 제 코드는 스스로 다소 난잡한 코드라고 생각이 드는데, 다행입니다 하하 |
@@ -0,0 +1,15 @@
+import { UNITS } from '../constants/system.js';
+
+/**
+ * number type의 가격을 입력받아 가격을 변환 후 '원'을 포함한 string type으로 변환
+ * 20000이라는 매개변수를 통해 '20,000원'을 반환
+ * @param {number} price 가격
+ * @returns {string}
+ */
+const priceFormatter = price => {
+ const formattedPrice = new Intl.NumberFormat().format(price);
+
+ return `${formattedPrice}${UNITS.won}`;
+};
+
+export default priceFormatter; | JavaScript | 저는 이 부분을 [Number.toLocaleString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString)을 적용했는데, 숫자 형식과 관련된 부분은 Intl 객체를 사용하는게 더 정확할 것 같네요 👍 (내부적으로 같은 메서드를 사용하는 거 같아요 ㅎㅎ) |
@@ -0,0 +1,24 @@
+const MENUS = Object.freeze({
+ appetizer: {
+ 양송이수프: 6_000,
+ 타파스: 5_500,
+ 시저샐러드: 8_000,
+ },
+ main: {
+ 티본스테이크: 55_000,
+ 바비큐립: 54_000,
+ 해산물파스타: 35_000,
+ 크리스마스파스타: 25_000,
+ },
+ dessert: {
+ 초코케이크: 15_000,
+ 아이스크림: 5_000,
+ },
+ beverage: {
+ 제로콜라: 3_000,
+ 레드와인: 60_000,
+ 샴페인: 25_000,
+ },
+});
+
+export default MENUS; | JavaScript | 혹시 menu도 data 폴더에 넣는 방향도 생각해 보셨을까요? 저 같은 경우엔 상수로 묶기엔 걸리는 부분들이 있었던 것 같아서요! 개인적으로 궁금해서 여쭤봅니다! 🙂 |
@@ -1,5 +1,15 @@
+import EventController from './controller/index.js';
+
class App {
- async run() {}
+ #controller;
+
+ constructor() {
+ this.#controller = new EventController();
+ }
+
+ async run() {
+ await this.#controller.startEvent();
+ }
}
export default App; | JavaScript | App이 정말 깔끔하네요..! 뒤에 숨겨진 코드들 보고 많이 배워갑니다! 🏃♂️ |
@@ -0,0 +1,52 @@
+import { PROMOTION_TITLES, TIME, UNITS } from './system.js';
+
+export const DISCOUNT_PRICES = Object.freeze({
+ dDay: 1_000,
+ dDayInc: 100,
+ week: 2_023,
+ special: 1_000,
+});
+
+export const BADGES = Object.freeze({
+ star: { title: '별', price: 5_000 },
+ tree: { title: '트리', price: 10_000 },
+ santa: { title: '산타', price: 20_000 },
+});
+
+export const TITLES = Object.freeze({
+ dDay: `${PROMOTION_TITLES[TIME.month]} 디데이 할인`,
+ weekday: '평일 할인',
+ weekend: '주말 할인',
+ special: '특별 할인',
+ giveaway: '증정 이벤트',
+});
+
+export const GIVEAWAYS = Object.freeze({
+ giveaway: '샴페인',
+ giveawayUnit: 1,
+ giveawayPrice: 120_000,
+});
+
+export const ORDER = Object.freeze({
+ minPrice: 10_000,
+ minQuantity: 1,
+ maxQuantity: 20,
+});
+
+export const DATES = Object.freeze({
+ startDate: 1,
+ endDate: 31,
+ christmas: 25,
+ specialDayIndex: 0,
+ weekendIndex: 5,
+});
+
+export const BENEFITS = Object.freeze({
+ menu: '<주문 메뉴>',
+ preTotalPrice: '<할인 전 총주문 금액>',
+ giveaway: '<증정 메뉴>',
+ benefitList: '<혜택 내역>',
+ totalBenefitPrice: '<총혜택 금액>',
+ totalPrice: '<할인 후 예상 결제 금액>',
+ badge: `<${TIME.month}${UNITS.month} 이벤트 배지>`,
+}); | JavaScript | `dDayInc`보다는 좀더 구체적인 상수명은 어떨까요? |
@@ -0,0 +1,52 @@
+import { PROMOTION_TITLES, TIME, UNITS } from './system.js';
+
+export const DISCOUNT_PRICES = Object.freeze({
+ dDay: 1_000,
+ dDayInc: 100,
+ week: 2_023,
+ special: 1_000,
+});
+
+export const BADGES = Object.freeze({
+ star: { title: '별', price: 5_000 },
+ tree: { title: '트리', price: 10_000 },
+ santa: { title: '산타', price: 20_000 },
+});
+
+export const TITLES = Object.freeze({
+ dDay: `${PROMOTION_TITLES[TIME.month]} 디데이 할인`,
+ weekday: '평일 할인',
+ weekend: '주말 할인',
+ special: '특별 할인',
+ giveaway: '증정 이벤트',
+});
+
+export const GIVEAWAYS = Object.freeze({
+ giveaway: '샴페인',
+ giveawayUnit: 1,
+ giveawayPrice: 120_000,
+});
+
+export const ORDER = Object.freeze({
+ minPrice: 10_000,
+ minQuantity: 1,
+ maxQuantity: 20,
+});
+
+export const DATES = Object.freeze({
+ startDate: 1,
+ endDate: 31,
+ christmas: 25,
+ specialDayIndex: 0,
+ weekendIndex: 5,
+});
+
+export const BENEFITS = Object.freeze({
+ menu: '<주문 메뉴>',
+ preTotalPrice: '<할인 전 총주문 금액>',
+ giveaway: '<증정 메뉴>',
+ benefitList: '<혜택 내역>',
+ totalBenefitPrice: '<총혜택 금액>',
+ totalPrice: '<할인 후 예상 결제 금액>',
+ badge: `<${TIME.month}${UNITS.month} 이벤트 배지>`,
+}); | JavaScript | 새해 이벤트까지는 생각안해봤는데 꼼꼼하십니다!👍 |
@@ -0,0 +1,15 @@
+import { UNITS } from '../constants/system.js';
+
+/**
+ * number type의 가격을 입력받아 가격을 변환 후 '원'을 포함한 string type으로 변환
+ * 20000이라는 매개변수를 통해 '20,000원'을 반환
+ * @param {number} price 가격
+ * @returns {string}
+ */
+const priceFormatter = price => {
+ const formattedPrice = new Intl.NumberFormat().format(price);
+
+ return `${formattedPrice}${UNITS.won}`;
+};
+
+export default priceFormatter; | JavaScript | 맞습니다! 석표님 말씀처럼 결국 `toLocaleString()`이 궁극적으로 `Intl.NumberFormat` API를 사용하더라구요 :)
어떻게보면 좀더 손쉬운 사용을 위한 `toLocaleString()` 메서드 사용이 더 목적에 부합할 수도 있다고 생각이 드네요 :) |
@@ -1,6 +1,9 @@
package bridge;
+import bridge.domain.constant.MoveCommand;
import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
/**
* 다리의 길이를 입력 받아서 다리를 생성해주는 역할을 한다.
@@ -18,6 +21,10 @@ public BridgeMaker(BridgeNumberGenerator bridgeNumberGenerator) {
* @return 입력받은 길이에 해당하는 다리 모양. 위 칸이면 "U", 아래 칸이면 "D"로 표현해야 한다.
*/
public List<String> makeBridge(int size) {
- return null;
+ return IntStream
+ .generate(bridgeNumberGenerator::generate)
+ .limit(size)
+ .mapToObj(MoveCommand::convertCommand)
+ .collect(Collectors.toList());
}
} | Java | 이 부분 객체지향적으로 설계를 잘하셨네요!! 가독성 아주 굿입니다 |
@@ -0,0 +1,95 @@
+package bridge.controller;
+
+import bridge.domain.model.Bridge;
+import bridge.domain.model.BridgeGame;
+import bridge.domain.constant.MoveCommand;
+import bridge.domain.constant.RetryCommand;
+import bridge.domain.constant.Status;
+import bridge.view.InputView;
+import bridge.view.OutputView;
+
+public class BridgeController {
+
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final BridgeGame bridgeGame;
+
+ public BridgeController() {
+ this.inputView = new InputView();
+ this.outputView = new OutputView();
+ this.bridgeGame = new BridgeGame();
+ }
+
+ public void crossBridge() {
+ outputView.printStartMessage();
+ Bridge bridge = createBridge();
+ startCrossingTheBridge(bridge);
+ }
+
+ private void startCrossingTheBridge(Bridge bridge) {
+ int count = 1;
+ Status status;
+ while (true) {
+ status = startGame(bridge);
+ if (status == Status.FAIL) {
+ if (restartGame() == RetryCommand.RETRY) {
+ count++;
+ continue;
+ }
+ }
+ break;
+ }
+ outputView.printResult(count, status, bridgeGame);
+ }
+
+ private RetryCommand restartGame() {
+ outputView.printRestart();
+ while (true) {
+ try {
+ String command = inputView.readGameCommand();
+ return RetryCommand.from(command);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e);
+ }
+ }
+ }
+
+ private Status startGame(Bridge bridge) {
+ Status status = Status.SUCCESS;
+ for (int idx = 0; idx < bridge.getSize(); idx++) {
+ MoveCommand moveCommand = getMoveCommand();
+ status = bridgeGame.move(idx, moveCommand, bridge);
+ outputView.printMap(bridgeGame);
+ if (bridgeGame.retry(status)) {
+ break;
+ }
+ }
+ return status;
+ }
+
+ private Bridge createBridge() {
+ outputView.printInputSize();
+ while (true) {
+ try {
+ int bridgeSize = inputView.readBridgeSize();
+ Bridge bridge = Bridge.createBridge(bridgeSize);
+ bridge.setBridge(bridgeSize);
+ return bridge;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e);
+ }
+ }
+ }
+
+ private MoveCommand getMoveCommand() {
+ outputView.printInputMoveCommand();
+ while (true) {
+ try {
+ String command = inputView.readMoving();
+ return MoveCommand.from(command);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e);
+ }
+ }
+ }
+} | Java | depth가 3이네요 ㅜㅜ 함수를 분리하셔야할거 같습니다 |
@@ -0,0 +1,41 @@
+package bridge.domain.model;
+
+import bridge.domain.constant.MoveCommand;
+import bridge.domain.constant.Status;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+public class GameDashboard {
+
+ private final List<Status> upResult = new ArrayList<>();
+ private final List<Status> downResult = new ArrayList<>();
+
+ public void updateResult(Status status, MoveCommand moveCommand) {
+ if (status == Status.SUCCESS) {
+ checkResult(status, moveCommand);
+ }
+ if (status == Status.FAIL) {
+ checkResult(status, moveCommand);
+ }
+ }
+
+ private void checkResult(Status status, MoveCommand moveCommand) {
+ if (moveCommand == MoveCommand.UP) {
+ upResult.add(status);
+ downResult.add(Status.SPACE);
+ }
+ if (moveCommand == MoveCommand.DOWN) {
+ upResult.add(Status.SPACE);
+ downResult.add(status);
+ }
+ }
+
+ public List<Status> getUpResult() {
+ return Collections.unmodifiableList(upResult);
+ }
+
+ public List<Status> getDownResult() {
+ return Collections.unmodifiableList(downResult);
+ }
+} | Java | 이 부분 좋네요! 저도 Map 을 외부로 뺄지 말지 고민하다가 안뺐는데 뺀 후에 Player가 가지고 있는 기능들을 옮겨주는게 더 좋았을거 같습니다. |
@@ -0,0 +1,95 @@
+package bridge.controller;
+
+import bridge.domain.model.Bridge;
+import bridge.domain.model.BridgeGame;
+import bridge.domain.constant.MoveCommand;
+import bridge.domain.constant.RetryCommand;
+import bridge.domain.constant.Status;
+import bridge.view.InputView;
+import bridge.view.OutputView;
+
+public class BridgeController {
+
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final BridgeGame bridgeGame;
+
+ public BridgeController() {
+ this.inputView = new InputView();
+ this.outputView = new OutputView();
+ this.bridgeGame = new BridgeGame();
+ }
+
+ public void crossBridge() {
+ outputView.printStartMessage();
+ Bridge bridge = createBridge();
+ startCrossingTheBridge(bridge);
+ }
+
+ private void startCrossingTheBridge(Bridge bridge) {
+ int count = 1;
+ Status status;
+ while (true) {
+ status = startGame(bridge);
+ if (status == Status.FAIL) {
+ if (restartGame() == RetryCommand.RETRY) {
+ count++;
+ continue;
+ }
+ }
+ break;
+ }
+ outputView.printResult(count, status, bridgeGame);
+ }
+
+ private RetryCommand restartGame() {
+ outputView.printRestart();
+ while (true) {
+ try {
+ String command = inputView.readGameCommand();
+ return RetryCommand.from(command);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e);
+ }
+ }
+ }
+
+ private Status startGame(Bridge bridge) {
+ Status status = Status.SUCCESS;
+ for (int idx = 0; idx < bridge.getSize(); idx++) {
+ MoveCommand moveCommand = getMoveCommand();
+ status = bridgeGame.move(idx, moveCommand, bridge);
+ outputView.printMap(bridgeGame);
+ if (bridgeGame.retry(status)) {
+ break;
+ }
+ }
+ return status;
+ }
+
+ private Bridge createBridge() {
+ outputView.printInputSize();
+ while (true) {
+ try {
+ int bridgeSize = inputView.readBridgeSize();
+ Bridge bridge = Bridge.createBridge(bridgeSize);
+ bridge.setBridge(bridgeSize);
+ return bridge;
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e);
+ }
+ }
+ }
+
+ private MoveCommand getMoveCommand() {
+ outputView.printInputMoveCommand();
+ while (true) {
+ try {
+ String command = inputView.readMoving();
+ return MoveCommand.from(command);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e);
+ }
+ }
+ }
+} | Java | 이 부분을 BridgeGame에서 진행하는 방법은 없었을까요??? |
@@ -0,0 +1,64 @@
+package bridge.view;
+
+import static bridge.view.ViewMessage.*;
+
+import bridge.domain.model.BridgeGame;
+import bridge.domain.model.GameDashboard;
+import bridge.domain.constant.Status;
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ * 사용자에게 게임 진행 상황과 결과를 출력하는 역할을 한다.
+ */
+public class OutputView {
+
+ public void printError(IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ }
+
+ public void printStartMessage() {
+ System.out.println(START_MESSAGE.getMessage());
+ }
+
+ public void printInputSize() {
+ System.out.println(INPUT_BRIDGE_SIZE_MESSAGE.getMessage());
+ }
+
+ public void printInputMoveCommand() {
+ System.out.println(INPUT_MOVE_COMMAND_MESSAGE.getMessage());
+ }
+
+ public void printRestart() {
+ System.out.println(INPUT_RETRY_COMMAND_MESSAGE.getMessage());
+ }
+
+ /**
+ * 현재까지 이동한 다리의 상태를 정해진 형식에 맞춰 출력한다.
+ * <p>
+ * 출력을 위해 필요한 메서드의 인자(parameter)는 자유롭게 추가하거나 변경할 수 있다.
+ */
+ public void printMap(BridgeGame bridgeGame) {
+ GameDashboard dashboard = bridgeGame.getGameDashboard();
+ System.out.printf(RESULT_FORMAT.getMessage(), convertToString(dashboard.getUpResult()));
+ System.out.printf(RESULT_FORMAT.getMessage(), convertToString(dashboard.getDownResult()));
+ }
+
+ /**
+ * 게임의 최종 결과를 정해진 형식에 맞춰 출력한다.
+ * <p>
+ * 출력을 위해 필요한 메서드의 인자(parameter)는 자유롭게 추가하거나 변경할 수 있다.
+ */
+ public void printResult(int count, Status status, BridgeGame bridgeGame) {
+ System.out.println(RESULT_MESSAGE.getMessage());
+ printMap(bridgeGame);
+ System.out.printf(SUCCESS_OR_FAIL.getMessage(), status.getMessage());
+ System.out.printf(TOTAL_ATTEMPTS_COUNT.getMessage(), count);
+ }
+
+ private String convertToString(List<Status> result) {
+ List<String> convertResult = result.stream().map(Status::getStatus)
+ .collect(Collectors.toList());
+ return String.join(DELIMITER.getMessage(), convertResult);
+ }
+} | Java | 매개값을 BridgeGame이 아닌 GameDashBoard로 받았으면 어땠을까요??? |
@@ -0,0 +1,23 @@
+package bridge.view;
+
+public enum ViewMessage {
+ START_MESSAGE("다리 건너기 게임을 시작합니다."),
+ INPUT_BRIDGE_SIZE_MESSAGE("다리의 길이를 입력해주세요."),
+ INPUT_MOVE_COMMAND_MESSAGE("이동할 칸을 선택해주세요. (위: U, 아래: D)"),
+ INPUT_RETRY_COMMAND_MESSAGE("게임을 다시 시도할지 여부를 입력해주세요. (재시도: R, 종료: Q)"),
+ RESULT_MESSAGE("최종 게임 결과"),
+ SUCCESS_OR_FAIL("게임 성공 여부: %s%n"),
+ TOTAL_ATTEMPTS_COUNT("총 시도한 횟수: %d%n"),
+ DELIMITER(" | "),
+ RESULT_FORMAT("[ %s ]%n");
+
+ private final String message;
+
+ ViewMessage(String message) {
+ this.message = message;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+} | Java | StringJoiner 를 쓰면 해당 부분을 한번에 해결할 수 있더라구요! |
@@ -0,0 +1,14 @@
+package step1;
+
+public class Print {
+
+ private int calculateResult;
+
+ public Print(int calculateResult) {
+ this.calculateResult = calculateResult;
+ }
+
+ public void printResult() {
+ System.out.println("calculateResult = " + calculateResult);
+ }
+} | Java | Print가 하나의 계산결과를 상태로 가지도록 구현하셨네요!
만약 Print를 통해 또 다른 계산 결과를 출력해야한다면 어떻게 될까요? Print라는 클래스의 책임에 맞는 역할을 하고 있다고 볼 수 있을까요? |
@@ -0,0 +1,50 @@
+package step1;
+
+import java.util.List;
+
+public class Calculator {
+
+ private CalculatorResource calculatorResource;
+
+ public Calculator(String stringCalculatorSentence) {
+ this.calculatorResource = new CalculatorResource(stringCalculatorSentence);
+ }
+
+ public int calculate() {
+
+ List<Integer> numberList = calculatorResource.getNumberArray();
+ List<String> operatorList = calculatorResource.getOperatorArray();
+
+ int operatorListIndex = 0;
+ int result = 0;
+
+ for (int i = 1; i < numberList.size(); i++) {
+
+ result = calcualteInit(numberList, result, i);
+
+ result = getResult(numberList, operatorList, operatorListIndex, result, i);
+ operatorListIndex++;
+ }
+ return result;
+ }
+
+ private int calcualteInit(List<Integer> numberList, int result, int i) {
+ if (i == 1) {
+ result = (numberList.get(i - 1));
+ }
+ return result;
+ }
+
+ private int getResult(List<Integer> numberList, List<String> operatorList, int operatorListIndex, int result, int i) {
+ if (operatorList.get(operatorListIndex).equals("+")) {
+ result = result + (numberList.get(i));
+ } else if (operatorList.get(operatorListIndex).equals("-")) {
+ result = result - (numberList.get(i));
+ } else if (operatorList.get(operatorListIndex).equals("*")) {
+ result = result * (numberList.get(i));
+ } else if (operatorList.get(operatorListIndex).equals("/")) {
+ result = result / (numberList.get(i));
+ }
+ return result;
+ }
+} | Java | java의 Enum 클래스를 사용하면 상태와 행위를 한곳에서 관리할 수 있는데요!
링크를 보시고 참고하셔서 enum 클래스를 사용해보면 좋을 것 같습니다 :)
https://techblog.woowahan.com/2527/ |
@@ -0,0 +1,50 @@
+package step1;
+
+import java.util.List;
+
+public class Calculator {
+
+ private CalculatorResource calculatorResource;
+
+ public Calculator(String stringCalculatorSentence) {
+ this.calculatorResource = new CalculatorResource(stringCalculatorSentence);
+ }
+
+ public int calculate() {
+
+ List<Integer> numberList = calculatorResource.getNumberArray();
+ List<String> operatorList = calculatorResource.getOperatorArray();
+
+ int operatorListIndex = 0;
+ int result = 0;
+
+ for (int i = 1; i < numberList.size(); i++) {
+
+ result = calcualteInit(numberList, result, i);
+
+ result = getResult(numberList, operatorList, operatorListIndex, result, i);
+ operatorListIndex++;
+ }
+ return result;
+ }
+
+ private int calcualteInit(List<Integer> numberList, int result, int i) {
+ if (i == 1) {
+ result = (numberList.get(i - 1));
+ }
+ return result;
+ }
+
+ private int getResult(List<Integer> numberList, List<String> operatorList, int operatorListIndex, int result, int i) {
+ if (operatorList.get(operatorListIndex).equals("+")) {
+ result = result + (numberList.get(i));
+ } else if (operatorList.get(operatorListIndex).equals("-")) {
+ result = result - (numberList.get(i));
+ } else if (operatorList.get(operatorListIndex).equals("*")) {
+ result = result * (numberList.get(i));
+ } else if (operatorList.get(operatorListIndex).equals("/")) {
+ result = result / (numberList.get(i));
+ }
+ return result;
+ }
+} | Java | 메서드의 파라미터의 개수를 2개 이하로 리팩터링해보는건 어떨까요?
클린 코드 책에서는 메서드의 파라미터 개수는 0~2개가 적절하며 4개 이상은 무조건적으로 피해야한다고 이야기합니다.
파라미터의 개수가 많을 수록 하나의 메서드에서 하는 일이 많아질 수 있고 코드를 읽기 어려워지기 때문입니다 :) |
@@ -0,0 +1,50 @@
+package step1;
+
+import java.util.List;
+
+public class Calculator {
+
+ private CalculatorResource calculatorResource;
+
+ public Calculator(String stringCalculatorSentence) {
+ this.calculatorResource = new CalculatorResource(stringCalculatorSentence);
+ }
+
+ public int calculate() {
+
+ List<Integer> numberList = calculatorResource.getNumberArray();
+ List<String> operatorList = calculatorResource.getOperatorArray();
+
+ int operatorListIndex = 0;
+ int result = 0;
+
+ for (int i = 1; i < numberList.size(); i++) {
+
+ result = calcualteInit(numberList, result, i);
+
+ result = getResult(numberList, operatorList, operatorListIndex, result, i);
+ operatorListIndex++;
+ }
+ return result;
+ }
+
+ private int calcualteInit(List<Integer> numberList, int result, int i) {
+ if (i == 1) {
+ result = (numberList.get(i - 1));
+ }
+ return result;
+ }
+
+ private int getResult(List<Integer> numberList, List<String> operatorList, int operatorListIndex, int result, int i) {
+ if (operatorList.get(operatorListIndex).equals("+")) {
+ result = result + (numberList.get(i));
+ } else if (operatorList.get(operatorListIndex).equals("-")) {
+ result = result - (numberList.get(i));
+ } else if (operatorList.get(operatorListIndex).equals("*")) {
+ result = result * (numberList.get(i));
+ } else if (operatorList.get(operatorListIndex).equals("/")) {
+ result = result / (numberList.get(i));
+ }
+ return result;
+ }
+} | Java | `계산기`가 하나의 `계산기 자원`을 상태로 가지도록 구현하셨네요 !
만약 계산기가 또 다른 자원에 대한 계산을 해야하는 상황이라면 어떻게 해야할까요?
현재 상태에서는 하나의 계산기 객체가 하나의 자원만을 계산할 수 있는데요.
여러 개의 자원에 대해 계산할 수 있도록 개선해보면 좋을 것 같습니다 :) |
@@ -0,0 +1,64 @@
+package step1;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class CalculatorResource {
+
+ private String sentence;
+ private String[] sentenceArray;
+ private List<Integer> numberArray;
+ private List<String> operatorArray;
+
+ public List<Integer> getNumberArray() {
+ return numberArray;
+ }
+
+ public List<String> getOperatorArray() {
+ return operatorArray;
+ }
+
+ public CalculatorResource(String sentence) {
+ this.sentence = sentence;
+ splitSentence();
+ creatNumberList();
+ creatOperatorList();
+ }
+
+ private void splitSentence() {
+ this.sentenceArray = this.sentence.split(" ");
+ }
+
+ public void creatNumberList() {
+ this.numberArray = new ArrayList<>();
+
+ for (String s : sentenceArray) {
+ char numberCheck = s.charAt(0);
+ validateNumber(numberArray, s, numberCheck);
+ }
+ this.numberArray = numberArray;
+ }
+
+ private void validateNumber(List<Integer> numberArray, String s, char numberCheck) {
+ if (numberCheck > 48 && numberCheck < 58) {
+ this.numberArray.add(Integer.parseInt(s));
+ }
+ }
+
+ public void creatOperatorList() {
+ this.operatorArray = new ArrayList<>();
+
+ for (String s : sentenceArray) {
+ char operatorCheck = s.charAt(0);
+ validateOperator(operatorArray, s, operatorCheck);
+ }
+ }
+
+ private void validateOperator(List<String> operatorArray, String s, char operatorCheck) {
+ if (operatorCheck < 48 || operatorCheck > 58) {
+ this.operatorArray.add(s);
+ }
+ }
+
+
+} | Java | CalculatorResource 클래스 네이밍은 추상화가 많이 되어 있는 클래스 명입니다.
클래스 내부를 보지 않으면 어떤 상태를 가지고 있는지 유추하기 힘듭니다. 조금 더 구체적인 클래스 명을 만들어보면 좋을 것 같아요 :) |
@@ -0,0 +1,64 @@
+package step1;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class CalculatorResource {
+
+ private String sentence;
+ private String[] sentenceArray;
+ private List<Integer> numberArray;
+ private List<String> operatorArray;
+
+ public List<Integer> getNumberArray() {
+ return numberArray;
+ }
+
+ public List<String> getOperatorArray() {
+ return operatorArray;
+ }
+
+ public CalculatorResource(String sentence) {
+ this.sentence = sentence;
+ splitSentence();
+ creatNumberList();
+ creatOperatorList();
+ }
+
+ private void splitSentence() {
+ this.sentenceArray = this.sentence.split(" ");
+ }
+
+ public void creatNumberList() {
+ this.numberArray = new ArrayList<>();
+
+ for (String s : sentenceArray) {
+ char numberCheck = s.charAt(0);
+ validateNumber(numberArray, s, numberCheck);
+ }
+ this.numberArray = numberArray;
+ }
+
+ private void validateNumber(List<Integer> numberArray, String s, char numberCheck) {
+ if (numberCheck > 48 && numberCheck < 58) {
+ this.numberArray.add(Integer.parseInt(s));
+ }
+ }
+
+ public void creatOperatorList() {
+ this.operatorArray = new ArrayList<>();
+
+ for (String s : sentenceArray) {
+ char operatorCheck = s.charAt(0);
+ validateOperator(operatorArray, s, operatorCheck);
+ }
+ }
+
+ private void validateOperator(List<String> operatorArray, String s, char operatorCheck) {
+ if (operatorCheck < 48 || operatorCheck > 58) {
+ this.operatorArray.add(s);
+ }
+ }
+
+
+} | Java | 객체가 생성된 이후에 두 변수는 사용되지 않고 있네요! 🤔
그렇다면 계산기 자원클래스에서 sentence와 sentenceArray를 상태로 가지고 있을 필요가 있을까요? |
@@ -0,0 +1,36 @@
+import EventCalendar from '../../src/domain/EventCalendar';
+import { CHRISTMAS_D_DAY, GIFT, SPECIAL } from '../../src/domain/Events';
+
+import {
+ EVENT_MONTH,
+ EVENT_NAMES,
+ EVENT_YEAR,
+} from '../../src/constants/event';
+import { MAIN_COURSES } from '../../src/constants/menus';
+
+describe('EventCalendar 테스트', () => {
+ test('getEventBenefit 기능 테스트', () => {
+ // given
+ const YEAR = EVENT_YEAR;
+ const MONTH = EVENT_MONTH;
+ const DATE = 25;
+ const TOTAL_PRICE = 130_000;
+ const ORDER_CATEGORIES = [MAIN_COURSES];
+
+ const RESULT = {
+ [EVENT_NAMES.CHRISTMAS_D_DAY]: CHRISTMAS_D_DAY.getEvent().getBenefit,
+ [EVENT_NAMES.SPECIAL]: SPECIAL.getEvent().getBenefit,
+ [EVENT_NAMES.GIFT]: GIFT.getEvent().getBenefit,
+ };
+
+ // when
+ const eventCalendar = new EventCalendar(YEAR, MONTH, DATE);
+ eventCalendar.setAvailableEvents({
+ totalPrice: TOTAL_PRICE,
+ orderCategories: ORDER_CATEGORIES,
+ });
+
+ //then
+ expect(eventCalendar.availableEvents).toEqual(RESULT);
+ });
+}); | JavaScript | 테스트 코드에서 실제 코드에서 사용되는 상수를 사용하는 것은 좋지 않아 보입니다. |
@@ -0,0 +1,117 @@
+import { EVENT_NAMES } from '../../src/constants/event';
+import EventPlanner from '../../src/services/EventPlanner';
+
+const ORDERS = [
+ { menu: '양송이수프', amount: 1 },
+ { menu: '타파스', amount: 1 },
+ { menu: '티본스테이크', amount: 2 },
+ { menu: '초코케이크', amount: 1 },
+ { menu: '아이스크림', amount: 1 },
+];
+
+async function getEventPlanner(orders) {
+ // given
+ const VISIT_DATE = 25;
+
+ // when
+ const eventPlanner = new EventPlanner(VISIT_DATE);
+ await eventPlanner.generateReceipt(orders);
+ await eventPlanner.generateBenefits();
+
+ return eventPlanner;
+}
+
+describe('EventPlanner 기능 테스트', () => {
+ test.each([32, 3.1])('validate - 정상 작동', async (input) => {
+ expect(() => new EventPlanner(input)).toThrow('[ERROR]');
+ });
+});
+
+describe('EventPlanner 혜택 조회 테스트', () => {
+ test('접근자 프로퍼티 테스트 - gift', async () => {
+ const gift = {
+ menu: '샴페인',
+ amount: 1,
+ price: 25_000,
+ };
+
+ const eventPlanner = await getEventPlanner(ORDERS);
+
+ expect(eventPlanner.gift).toEqual(gift);
+ });
+
+ test('접근자 프로퍼티 테스트 - benefits', async () => {
+ const benefits = {
+ [EVENT_NAMES.CHRISTMAS_D_DAY]: { amount: 1, price: 3400 },
+ [EVENT_NAMES.SPECIAL]: { amount: 1, price: 1000 },
+ [EVENT_NAMES.WEEKDAY]: { amount: 2, price: 2023 },
+ [EVENT_NAMES.GIFT]: {
+ menu: '샴페인',
+ amount: 1,
+ price: 25_000,
+ },
+ };
+
+ const eventPlanner = await getEventPlanner(ORDERS);
+
+ expect(eventPlanner.benefits).toEqual(benefits);
+ });
+
+ test('접근자 프로퍼티 테스트 - totalBenefitMoney', async () => {
+ const totalBenefitMoney = 33_446;
+
+ const eventPlanner = await getEventPlanner(ORDERS);
+
+ expect(eventPlanner.totalBenefitMoney).toBe(totalBenefitMoney);
+ });
+
+ test('접근자 프로퍼티 테스트 - payment', async () => {
+ const originalPrice = 141_500;
+ const discountAmount = 8_446;
+
+ const eventPlanner = await getEventPlanner(ORDERS);
+
+ expect(eventPlanner.payment).toBe(originalPrice - discountAmount);
+ });
+
+ test.each([
+ {
+ orders: [
+ { menu: '양송이수프', amount: 1 },
+ { menu: '타파스', amount: 1 },
+ { menu: '티본스테이크', amount: 2 },
+ { menu: '초코케이크', amount: 1 },
+ { menu: '아이스크림', amount: 1 },
+ ],
+ badge: '산타',
+ },
+ {
+ orders: [
+ { menu: '양송이수프', amount: 1 },
+ { menu: '타파스', amount: 1 },
+ { menu: '티본스테이크', amount: 1 },
+ { menu: '아이스크림', amount: 4 },
+ ],
+ badge: '트리',
+ },
+ {
+ orders: [
+ { menu: '양송이수프', amount: 1 },
+ { menu: '타파스', amount: 1 },
+ { menu: '아이스크림', amount: 1 },
+ ],
+ badge: '별',
+ },
+ {
+ orders: [
+ { menu: '양송이수프', amount: 1 },
+ { menu: '타파스', amount: 1 },
+ ],
+ badge: '없음',
+ },
+ ])('접근자 프로퍼티 테스트 - badge', async ({ orders, badge }) => {
+ const eventPlanner = await getEventPlanner(orders);
+
+ expect(eventPlanner.badge).toBe(badge);
+ });
+}); | JavaScript | "\_"새롭게 배워갑니다! |
@@ -0,0 +1,117 @@
+import { EVENT_NAMES } from '../constants/event.js';
+import { DESSERTS, MAIN_COURSES } from '../constants/menus.js';
+
+export const CHRISTMAS_D_DAY = {
+ getBenefit({ date }) {
+ const baseAmount = 1000;
+ const weightAmount = 100;
+
+ return {
+ amount: 1,
+ price: baseAmount + weightAmount * (date - 1),
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.CHRISTMAS_D_DAY,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ isChristmasPeriod }) {
+ return isChristmasPeriod === true;
+ },
+};
+
+export const WEEKDAY = {
+ getBenefit({ orderCntByCategory }) {
+ const discountAmount = 2_023;
+ return {
+ amount: orderCntByCategory[DESSERTS],
+ price: discountAmount,
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.WEEKDAY,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ isWeekend, orderCategories }) {
+ return isWeekend === false && orderCategories.includes(DESSERTS);
+ },
+};
+
+export const WEEKEND = {
+ getBenefit({ orderCntByCategory }) {
+ const discountAmount = 2_023;
+ return {
+ amount: orderCntByCategory[MAIN_COURSES],
+ price: discountAmount,
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.WEEKEND,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ isWeekend, orderCategories }) {
+ return isWeekend === true && orderCategories.includes(MAIN_COURSES);
+ },
+};
+
+export const SPECIAL = {
+ getBenefit() {
+ const discountAmount = 1_000;
+ return {
+ amount: 1,
+ price: discountAmount,
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.SPECIAL,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ isSpecialDate }) {
+ return isSpecialDate === true;
+ },
+};
+
+export const GIFT = {
+ getBenefit() {
+ return {
+ menu: '샴페인',
+ amount: 1,
+ price: 25_000,
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.GIFT,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ totalPrice }) {
+ return totalPrice >= 120_000;
+ },
+};
+
+export const ALL_EVENTS = Object.freeze({
+ CHRISTMAS_D_DAY,
+ WEEKDAY,
+ WEEKEND,
+ SPECIAL,
+ GIFT,
+}); | JavaScript | isWeekend === true는 불필요해 보이는데, 사용하신 이유가 있으신가요? |
@@ -0,0 +1,117 @@
+import { EVENT_NAMES } from '../constants/event.js';
+import { DESSERTS, MAIN_COURSES } from '../constants/menus.js';
+
+export const CHRISTMAS_D_DAY = {
+ getBenefit({ date }) {
+ const baseAmount = 1000;
+ const weightAmount = 100;
+
+ return {
+ amount: 1,
+ price: baseAmount + weightAmount * (date - 1),
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.CHRISTMAS_D_DAY,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ isChristmasPeriod }) {
+ return isChristmasPeriod === true;
+ },
+};
+
+export const WEEKDAY = {
+ getBenefit({ orderCntByCategory }) {
+ const discountAmount = 2_023;
+ return {
+ amount: orderCntByCategory[DESSERTS],
+ price: discountAmount,
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.WEEKDAY,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ isWeekend, orderCategories }) {
+ return isWeekend === false && orderCategories.includes(DESSERTS);
+ },
+};
+
+export const WEEKEND = {
+ getBenefit({ orderCntByCategory }) {
+ const discountAmount = 2_023;
+ return {
+ amount: orderCntByCategory[MAIN_COURSES],
+ price: discountAmount,
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.WEEKEND,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ isWeekend, orderCategories }) {
+ return isWeekend === true && orderCategories.includes(MAIN_COURSES);
+ },
+};
+
+export const SPECIAL = {
+ getBenefit() {
+ const discountAmount = 1_000;
+ return {
+ amount: 1,
+ price: discountAmount,
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.SPECIAL,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ isSpecialDate }) {
+ return isSpecialDate === true;
+ },
+};
+
+export const GIFT = {
+ getBenefit() {
+ return {
+ menu: '샴페인',
+ amount: 1,
+ price: 25_000,
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.GIFT,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ totalPrice }) {
+ return totalPrice >= 120_000;
+ },
+};
+
+export const ALL_EVENTS = Object.freeze({
+ CHRISTMAS_D_DAY,
+ WEEKDAY,
+ WEEKEND,
+ SPECIAL,
+ GIFT,
+}); | JavaScript | 매직 넘버를 사용하시는 것 같으신데요, 혹시 본인만에 기준이 있으실까요? 이곳에서만 따로 분리를 하지 않으신 것 같아서요. |
@@ -0,0 +1,47 @@
+import { Console } from '@woowacourse/mission-utils';
+import MESSAGES from '../constants/messages.js';
+
+const OutputView = {
+ printResult(msgObj, result) {
+ const { title, printMsg } = msgObj;
+
+ Console.print(title);
+ Console.print(printMsg(result));
+ },
+
+ printStart() {
+ Console.print(MESSAGES.outputs.sayHi);
+ },
+
+ printMenus({ visitDate, menus }) {
+ Console.print(MESSAGES.outputs.eventPreview(visitDate));
+
+ this.printResult(MESSAGES.outputs.menus, menus);
+ },
+
+ printOriginalPrice(price) {
+ this.printResult(MESSAGES.outputs.originalPrice, price);
+ },
+
+ printGift(gift) {
+ this.printResult(MESSAGES.outputs.gift, gift);
+ },
+
+ printBenefits(benefits) {
+ this.printResult(MESSAGES.outputs.benefits, benefits);
+ },
+
+ printTotalBenefitMoney(money) {
+ this.printResult(MESSAGES.outputs.totalBenefitMoney, money);
+ },
+
+ printPayment(money) {
+ this.printResult(MESSAGES.outputs.payment, money);
+ },
+
+ printBadge(badge) {
+ this.printResult(MESSAGES.outputs.badge, badge);
+ },
+};
+
+export default OutputView; | JavaScript | 이런식으로 보내면 조금 더 깔끔해지는군요...!!! |
@@ -0,0 +1,94 @@
+import OrderItem from './OrderItem.js';
+
+import MESSAGES from '../constants/messages.js';
+
+import throwError from '../utils/throwError.js';
+import {
+ hasDuplicatedMenu,
+ hasOnlyBeverages,
+ isTotalAmountOfMenusValid,
+} from '../utils/validators.js';
+
+class Receipt {
+ #orders;
+
+ #orderItems;
+
+ constructor(orders) {
+ this.#validate(orders);
+ this.#orders = orders;
+ this.#orderItems = [];
+ }
+
+ #validate(orders) {
+ if (!isTotalAmountOfMenusValid(orders))
+ throwError(MESSAGES.errors.invalidOrders);
+
+ if (hasDuplicatedMenu(orders)) throwError(MESSAGES.errors.invalidOrders);
+
+ if (hasOnlyBeverages(orders)) throwError(MESSAGES.errors.invalidOrders);
+ }
+
+ generateOrders() {
+ this.#orderItems = this.#orders.map(
+ ({ menu, amount }) => new OrderItem(menu, amount),
+ );
+ }
+
+ get totalPrice() {
+ return this.#orderItems.reduce(
+ (totalPrice, orderItem) => totalPrice + orderItem.totalPrice,
+ 0,
+ );
+ }
+
+ get receipt() {
+ const receipt = {};
+
+ this.#orderItems.forEach((orderItem) => {
+ const { category, menu, amount } = orderItem.item;
+
+ if (!Array.isArray(receipt[category])) {
+ receipt[category] = [];
+ }
+
+ receipt[category].push({ menu, amount });
+ });
+
+ return receipt;
+ }
+
+ get orderCategories() {
+ const categories = new Set();
+
+ this.#orderItems.forEach((orderItem) => {
+ const { category } = orderItem.item;
+ categories.add(category);
+ });
+
+ return [...categories];
+ }
+
+ get orderCntByCategory() {
+ const orderCnt = {};
+
+ this.#orderItems.forEach((orderItem) => {
+ const { category, amount } = orderItem.item;
+
+ if (!orderCnt[category]) orderCnt[category] = 0;
+
+ orderCnt[category] += amount;
+ });
+
+ return orderCnt;
+ }
+
+ get menus() {
+ return this.#orderItems.map((orderItem) => {
+ const { menu, amount } = orderItem.item;
+ return { menu, amount };
+ });
+ }
+}
+
+export default Receipt; | JavaScript | get의 사용법 배우고 갑니다...! |
@@ -0,0 +1,46 @@
+import MESSAGES from '../constants/messages.js';
+import { CATEGORIES, MENUS } from '../constants/menus.js';
+
+import { getValueOfField } from '../utils/object.js';
+import throwError from '../utils/throwError.js';
+import { isMenuExists } from '../utils/validators.js';
+
+class OrderItem {
+ #category;
+
+ #menu;
+
+ #amount;
+
+ constructor(menu, amount) {
+ this.#validate(menu);
+ this.#setCategory(menu);
+ this.#menu = menu;
+ this.#amount = amount;
+ }
+
+ #validate(menu) {
+ if (!isMenuExists(menu)) throwError(MESSAGES.errors.invalidMenu);
+ }
+
+ #setCategory(menu) {
+ this.#category = CATEGORIES.find((category) =>
+ getValueOfField(MENUS, `${category}.${menu}`),
+ );
+ }
+
+ get totalPrice() {
+ const price = getValueOfField(MENUS, `${this.#category}.${this.#menu}`);
+ return price * this.#amount;
+ }
+
+ get item() {
+ return {
+ category: this.#category,
+ menu: this.#menu,
+ amount: this.#amount,
+ };
+ }
+}
+
+export default OrderItem; | JavaScript | get set 함수를 이렇게 지정할 수 있다는 걸 처음 알게되었네요! |
@@ -0,0 +1,38 @@
+/**
+ * 두 객체가 같은 값을 가지고 있는지 얕게 비교
+ * @param {object} obj1
+ * @param {object} obj2
+ */
+export const shallowEqual = (objA, objB) => {
+ let result = true;
+
+ // 두 객체의 key 개수 비교
+ const keysA = Object.keys(objA);
+ const keysB = Object.keys(objB);
+ if (keysA.length !== keysB.length) result = false;
+
+ // 두 객체의 value 값 비교
+ keysA.forEach((key) => {
+ if (objA[key] !== objB[key]) result = false;
+ });
+
+ return result;
+};
+
+/**
+ * 점 표기법(.)을 사용해서 중첩 객체의 값을 찾는 함수
+ * 참고: https://elvanov.com/2286
+ * @param {object} obj
+ * @param {string} field
+ */
+export const getValueOfField = (obj, field) => {
+ if (!field) {
+ return null;
+ }
+
+ const keys = field.split('.');
+
+ return keys.reduce((curObj, curKey) => (curObj ? curObj[curKey] : null), obj);
+};
+
+export const isEmptyObject = (obj) => JSON.stringify(obj) === '{}'; | JavaScript | 내용 잘 봤습니다 ㅎㅎ |
@@ -0,0 +1,36 @@
+import EventCalendar from '../../src/domain/EventCalendar';
+import { CHRISTMAS_D_DAY, GIFT, SPECIAL } from '../../src/domain/Events';
+
+import {
+ EVENT_MONTH,
+ EVENT_NAMES,
+ EVENT_YEAR,
+} from '../../src/constants/event';
+import { MAIN_COURSES } from '../../src/constants/menus';
+
+describe('EventCalendar 테스트', () => {
+ test('getEventBenefit 기능 테스트', () => {
+ // given
+ const YEAR = EVENT_YEAR;
+ const MONTH = EVENT_MONTH;
+ const DATE = 25;
+ const TOTAL_PRICE = 130_000;
+ const ORDER_CATEGORIES = [MAIN_COURSES];
+
+ const RESULT = {
+ [EVENT_NAMES.CHRISTMAS_D_DAY]: CHRISTMAS_D_DAY.getEvent().getBenefit,
+ [EVENT_NAMES.SPECIAL]: SPECIAL.getEvent().getBenefit,
+ [EVENT_NAMES.GIFT]: GIFT.getEvent().getBenefit,
+ };
+
+ // when
+ const eventCalendar = new EventCalendar(YEAR, MONTH, DATE);
+ eventCalendar.setAvailableEvents({
+ totalPrice: TOTAL_PRICE,
+ orderCategories: ORDER_CATEGORIES,
+ });
+
+ //then
+ expect(eventCalendar.availableEvents).toEqual(RESULT);
+ });
+}); | JavaScript | 테스트 코드의 의존성을 줄여야 하기 때문일까요? 그렇게 생각하시는 이유가 궁금합니다..! |
@@ -0,0 +1,117 @@
+import { EVENT_NAMES } from '../constants/event.js';
+import { DESSERTS, MAIN_COURSES } from '../constants/menus.js';
+
+export const CHRISTMAS_D_DAY = {
+ getBenefit({ date }) {
+ const baseAmount = 1000;
+ const weightAmount = 100;
+
+ return {
+ amount: 1,
+ price: baseAmount + weightAmount * (date - 1),
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.CHRISTMAS_D_DAY,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ isChristmasPeriod }) {
+ return isChristmasPeriod === true;
+ },
+};
+
+export const WEEKDAY = {
+ getBenefit({ orderCntByCategory }) {
+ const discountAmount = 2_023;
+ return {
+ amount: orderCntByCategory[DESSERTS],
+ price: discountAmount,
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.WEEKDAY,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ isWeekend, orderCategories }) {
+ return isWeekend === false && orderCategories.includes(DESSERTS);
+ },
+};
+
+export const WEEKEND = {
+ getBenefit({ orderCntByCategory }) {
+ const discountAmount = 2_023;
+ return {
+ amount: orderCntByCategory[MAIN_COURSES],
+ price: discountAmount,
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.WEEKEND,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ isWeekend, orderCategories }) {
+ return isWeekend === true && orderCategories.includes(MAIN_COURSES);
+ },
+};
+
+export const SPECIAL = {
+ getBenefit() {
+ const discountAmount = 1_000;
+ return {
+ amount: 1,
+ price: discountAmount,
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.SPECIAL,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ isSpecialDate }) {
+ return isSpecialDate === true;
+ },
+};
+
+export const GIFT = {
+ getBenefit() {
+ return {
+ menu: '샴페인',
+ amount: 1,
+ price: 25_000,
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.GIFT,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ totalPrice }) {
+ return totalPrice >= 120_000;
+ },
+};
+
+export const ALL_EVENTS = Object.freeze({
+ CHRISTMAS_D_DAY,
+ WEEKDAY,
+ WEEKEND,
+ SPECIAL,
+ GIFT,
+}); | JavaScript | 물론 Truthy를 사용할 수도 있는 상황이지만, 실제로 운영하는 서비스라면 상태가 이상하거나 서버에서 잘못된 값이 날아왔을 때 잡을 수 있는 코드여야 한다고 생각했습니다! 그래서 타입과 값을 정확히 검사하는 방식으로 작성했어요. |
@@ -0,0 +1,117 @@
+import { EVENT_NAMES } from '../constants/event.js';
+import { DESSERTS, MAIN_COURSES } from '../constants/menus.js';
+
+export const CHRISTMAS_D_DAY = {
+ getBenefit({ date }) {
+ const baseAmount = 1000;
+ const weightAmount = 100;
+
+ return {
+ amount: 1,
+ price: baseAmount + weightAmount * (date - 1),
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.CHRISTMAS_D_DAY,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ isChristmasPeriod }) {
+ return isChristmasPeriod === true;
+ },
+};
+
+export const WEEKDAY = {
+ getBenefit({ orderCntByCategory }) {
+ const discountAmount = 2_023;
+ return {
+ amount: orderCntByCategory[DESSERTS],
+ price: discountAmount,
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.WEEKDAY,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ isWeekend, orderCategories }) {
+ return isWeekend === false && orderCategories.includes(DESSERTS);
+ },
+};
+
+export const WEEKEND = {
+ getBenefit({ orderCntByCategory }) {
+ const discountAmount = 2_023;
+ return {
+ amount: orderCntByCategory[MAIN_COURSES],
+ price: discountAmount,
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.WEEKEND,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ isWeekend, orderCategories }) {
+ return isWeekend === true && orderCategories.includes(MAIN_COURSES);
+ },
+};
+
+export const SPECIAL = {
+ getBenefit() {
+ const discountAmount = 1_000;
+ return {
+ amount: 1,
+ price: discountAmount,
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.SPECIAL,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ isSpecialDate }) {
+ return isSpecialDate === true;
+ },
+};
+
+export const GIFT = {
+ getBenefit() {
+ return {
+ menu: '샴페인',
+ amount: 1,
+ price: 25_000,
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.GIFT,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ totalPrice }) {
+ return totalPrice >= 120_000;
+ },
+};
+
+export const ALL_EVENTS = Object.freeze({
+ CHRISTMAS_D_DAY,
+ WEEKDAY,
+ WEEKEND,
+ SPECIAL,
+ GIFT,
+}); | JavaScript | 비즈니스와 관련한 중요한 로직이기 때문에 그 정보가 빠르게 보여야 하면서 다른 곳에서 재사용되지 않는 수는 상수로 빼지 않았습니다.
만약 '증정품 수령 최소 주문 금액'이라는 이름의 상수를 만든다면 그 의미는 담고 있겠지만, 그게 얼마인지 알기 위해서는 다른 파일을 열어 보거나 시선을 이동해야 하는 불편함이 생길 거라 생각했습니다. :)
비슷한 결정을 내린 사례로 EventPlanner의 getBadge 함수가 있습니다.😄 |
@@ -0,0 +1,117 @@
+import { EVENT_NAMES } from '../constants/event.js';
+import { DESSERTS, MAIN_COURSES } from '../constants/menus.js';
+
+export const CHRISTMAS_D_DAY = {
+ getBenefit({ date }) {
+ const baseAmount = 1000;
+ const weightAmount = 100;
+
+ return {
+ amount: 1,
+ price: baseAmount + weightAmount * (date - 1),
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.CHRISTMAS_D_DAY,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ isChristmasPeriod }) {
+ return isChristmasPeriod === true;
+ },
+};
+
+export const WEEKDAY = {
+ getBenefit({ orderCntByCategory }) {
+ const discountAmount = 2_023;
+ return {
+ amount: orderCntByCategory[DESSERTS],
+ price: discountAmount,
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.WEEKDAY,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ isWeekend, orderCategories }) {
+ return isWeekend === false && orderCategories.includes(DESSERTS);
+ },
+};
+
+export const WEEKEND = {
+ getBenefit({ orderCntByCategory }) {
+ const discountAmount = 2_023;
+ return {
+ amount: orderCntByCategory[MAIN_COURSES],
+ price: discountAmount,
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.WEEKEND,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ isWeekend, orderCategories }) {
+ return isWeekend === true && orderCategories.includes(MAIN_COURSES);
+ },
+};
+
+export const SPECIAL = {
+ getBenefit() {
+ const discountAmount = 1_000;
+ return {
+ amount: 1,
+ price: discountAmount,
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.SPECIAL,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ isSpecialDate }) {
+ return isSpecialDate === true;
+ },
+};
+
+export const GIFT = {
+ getBenefit() {
+ return {
+ menu: '샴페인',
+ amount: 1,
+ price: 25_000,
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.GIFT,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ totalPrice }) {
+ return totalPrice >= 120_000;
+ },
+};
+
+export const ALL_EVENTS = Object.freeze({
+ CHRISTMAS_D_DAY,
+ WEEKDAY,
+ WEEKEND,
+ SPECIAL,
+ GIFT,
+}); | JavaScript | 아하 그렇군요. 그렇다면 이렇게는 어떠신가요?
```
isEventAvailable({ totalPrice }) {
const evenAvaliableAmount = 120_000;
return totalPrice >= evenAvaliableAmount;
```
불필요한 한 줄이라고 생각하실 수 있지만, 말씀하신 문제를 해결하면서도 의미를 담을 수 있다고 생각했습니다! |
@@ -0,0 +1,36 @@
+import EventCalendar from '../../src/domain/EventCalendar';
+import { CHRISTMAS_D_DAY, GIFT, SPECIAL } from '../../src/domain/Events';
+
+import {
+ EVENT_MONTH,
+ EVENT_NAMES,
+ EVENT_YEAR,
+} from '../../src/constants/event';
+import { MAIN_COURSES } from '../../src/constants/menus';
+
+describe('EventCalendar 테스트', () => {
+ test('getEventBenefit 기능 테스트', () => {
+ // given
+ const YEAR = EVENT_YEAR;
+ const MONTH = EVENT_MONTH;
+ const DATE = 25;
+ const TOTAL_PRICE = 130_000;
+ const ORDER_CATEGORIES = [MAIN_COURSES];
+
+ const RESULT = {
+ [EVENT_NAMES.CHRISTMAS_D_DAY]: CHRISTMAS_D_DAY.getEvent().getBenefit,
+ [EVENT_NAMES.SPECIAL]: SPECIAL.getEvent().getBenefit,
+ [EVENT_NAMES.GIFT]: GIFT.getEvent().getBenefit,
+ };
+
+ // when
+ const eventCalendar = new EventCalendar(YEAR, MONTH, DATE);
+ eventCalendar.setAvailableEvents({
+ totalPrice: TOTAL_PRICE,
+ orderCategories: ORDER_CATEGORIES,
+ });
+
+ //then
+ expect(eventCalendar.availableEvents).toEqual(RESULT);
+ });
+}); | JavaScript | 네 의존성 문제라고 생각합니다.
저는 상수 자체도 하나의 모듈이라고 생각하는데요,
하나의 모듈이 실제 코드와, 테스트 코드 두 군데 모두 의존하는 것은 좋아보이지 않기 때문이기도 하고,
특히나 테스트는 독립적이어야 하기 때문이기도 합니다! |
@@ -0,0 +1,83 @@
+import deepFreeze from '../utils/deepFreeze.js';
+import { EVENT_MONTH } from './event.js';
+
+const MESSAGES = deepFreeze({
+ // InputView
+ inputs: {
+ getVisitDate: `${EVENT_MONTH}월 중 식당 예상 방문 날짜는 언제인가요? (숫자만 입력해 주세요!)\n`,
+ getOrders:
+ '주문하실 메뉴를 메뉴와 개수를 알려 주세요. (e.g. 해산물파스타-2,레드와인-1,초코케이크-1)\n',
+ },
+
+ // OutputView
+ outputs: {
+ sayHi: `안녕하세요! 우테코 식당 ${EVENT_MONTH}월 이벤트 플래너입니다.`,
+
+ eventPreview: (date) =>
+ `${EVENT_MONTH}월 ${date}일에 우테코 식당에서 받을 이벤트 혜택 미리 보기!\n`,
+
+ menus: {
+ title: '<주문 메뉴>',
+ printMsg: (menus) =>
+ menus.reduce(
+ (acc, { menu, amount }) => `${acc}${menu} ${amount}개\n`,
+ '',
+ ),
+ },
+
+ originalPrice: {
+ title: '<할인 전 총주문 금액>',
+ printMsg: (price) => `${price.toLocaleString()}원\n`,
+ },
+
+ gift: {
+ title: '<증정 메뉴>',
+ printMsg: (gift) => {
+ if (!gift) return '없음\n';
+
+ return `${gift.menu} ${gift.amount}개\n`;
+ },
+ },
+
+ benefits: {
+ title: '<혜택 내역>',
+ printMsg: (benefits) => {
+ if (!benefits) return '없음\n';
+
+ return Object.entries(benefits).reduce(
+ (acc, [eventName, { amount, price }]) =>
+ `${acc}${eventName}: -${(amount * price).toLocaleString()}원\n`,
+ '',
+ );
+ },
+ },
+
+ totalBenefitMoney: {
+ title: '<총혜택 금액>',
+ printMsg: (money) => {
+ if (!money) return '0원\n';
+
+ return `-${money.toLocaleString()}원\n`;
+ },
+ },
+
+ payment: {
+ title: '<할인 후 예상 결제 금액>',
+ printMsg: (money) => `${money.toLocaleString()}원\n`,
+ },
+
+ badge: {
+ title: '<12월 이벤트 배지>',
+ printMsg: (badge) => `${badge}`,
+ },
+ },
+
+ // Error
+ errors: {
+ prefix: '[ERROR]',
+ invalidDate: '유효하지 않은 날짜입니다. 다시 입력해 주세요.',
+ invalidOrders: '유효하지 않은 주문입니다. 다시 입력해 주세요.',
+ },
+});
+
+export default MESSAGES; | JavaScript | EVENT_MONTH는 상수보다는 12월로 바로 넣는 것도 고려해보시면 좋을 것 같아요
이 부분에 대해서 많이 고민했었는데, 해당 크리스마스 이벤트는 내년에도 개최될 수 있으니까 년도는 바뀌더라도, 크리스마스니까 12월은 안변하겠다 싶었습니다! |
@@ -0,0 +1,83 @@
+import deepFreeze from '../utils/deepFreeze.js';
+import { EVENT_MONTH } from './event.js';
+
+const MESSAGES = deepFreeze({
+ // InputView
+ inputs: {
+ getVisitDate: `${EVENT_MONTH}월 중 식당 예상 방문 날짜는 언제인가요? (숫자만 입력해 주세요!)\n`,
+ getOrders:
+ '주문하실 메뉴를 메뉴와 개수를 알려 주세요. (e.g. 해산물파스타-2,레드와인-1,초코케이크-1)\n',
+ },
+
+ // OutputView
+ outputs: {
+ sayHi: `안녕하세요! 우테코 식당 ${EVENT_MONTH}월 이벤트 플래너입니다.`,
+
+ eventPreview: (date) =>
+ `${EVENT_MONTH}월 ${date}일에 우테코 식당에서 받을 이벤트 혜택 미리 보기!\n`,
+
+ menus: {
+ title: '<주문 메뉴>',
+ printMsg: (menus) =>
+ menus.reduce(
+ (acc, { menu, amount }) => `${acc}${menu} ${amount}개\n`,
+ '',
+ ),
+ },
+
+ originalPrice: {
+ title: '<할인 전 총주문 금액>',
+ printMsg: (price) => `${price.toLocaleString()}원\n`,
+ },
+
+ gift: {
+ title: '<증정 메뉴>',
+ printMsg: (gift) => {
+ if (!gift) return '없음\n';
+
+ return `${gift.menu} ${gift.amount}개\n`;
+ },
+ },
+
+ benefits: {
+ title: '<혜택 내역>',
+ printMsg: (benefits) => {
+ if (!benefits) return '없음\n';
+
+ return Object.entries(benefits).reduce(
+ (acc, [eventName, { amount, price }]) =>
+ `${acc}${eventName}: -${(amount * price).toLocaleString()}원\n`,
+ '',
+ );
+ },
+ },
+
+ totalBenefitMoney: {
+ title: '<총혜택 금액>',
+ printMsg: (money) => {
+ if (!money) return '0원\n';
+
+ return `-${money.toLocaleString()}원\n`;
+ },
+ },
+
+ payment: {
+ title: '<할인 후 예상 결제 금액>',
+ printMsg: (money) => `${money.toLocaleString()}원\n`,
+ },
+
+ badge: {
+ title: '<12월 이벤트 배지>',
+ printMsg: (badge) => `${badge}`,
+ },
+ },
+
+ // Error
+ errors: {
+ prefix: '[ERROR]',
+ invalidDate: '유효하지 않은 날짜입니다. 다시 입력해 주세요.',
+ invalidOrders: '유효하지 않은 주문입니다. 다시 입력해 주세요.',
+ },
+});
+
+export default MESSAGES; | JavaScript | toLocaleString 부분이 가격을 반환해줄때는 다 쓰이는데, 따로 모듈화 시키는 것도 좋을 것 같아요! |
@@ -0,0 +1,83 @@
+import deepFreeze from '../utils/deepFreeze.js';
+import { EVENT_MONTH } from './event.js';
+
+const MESSAGES = deepFreeze({
+ // InputView
+ inputs: {
+ getVisitDate: `${EVENT_MONTH}월 중 식당 예상 방문 날짜는 언제인가요? (숫자만 입력해 주세요!)\n`,
+ getOrders:
+ '주문하실 메뉴를 메뉴와 개수를 알려 주세요. (e.g. 해산물파스타-2,레드와인-1,초코케이크-1)\n',
+ },
+
+ // OutputView
+ outputs: {
+ sayHi: `안녕하세요! 우테코 식당 ${EVENT_MONTH}월 이벤트 플래너입니다.`,
+
+ eventPreview: (date) =>
+ `${EVENT_MONTH}월 ${date}일에 우테코 식당에서 받을 이벤트 혜택 미리 보기!\n`,
+
+ menus: {
+ title: '<주문 메뉴>',
+ printMsg: (menus) =>
+ menus.reduce(
+ (acc, { menu, amount }) => `${acc}${menu} ${amount}개\n`,
+ '',
+ ),
+ },
+
+ originalPrice: {
+ title: '<할인 전 총주문 금액>',
+ printMsg: (price) => `${price.toLocaleString()}원\n`,
+ },
+
+ gift: {
+ title: '<증정 메뉴>',
+ printMsg: (gift) => {
+ if (!gift) return '없음\n';
+
+ return `${gift.menu} ${gift.amount}개\n`;
+ },
+ },
+
+ benefits: {
+ title: '<혜택 내역>',
+ printMsg: (benefits) => {
+ if (!benefits) return '없음\n';
+
+ return Object.entries(benefits).reduce(
+ (acc, [eventName, { amount, price }]) =>
+ `${acc}${eventName}: -${(amount * price).toLocaleString()}원\n`,
+ '',
+ );
+ },
+ },
+
+ totalBenefitMoney: {
+ title: '<총혜택 금액>',
+ printMsg: (money) => {
+ if (!money) return '0원\n';
+
+ return `-${money.toLocaleString()}원\n`;
+ },
+ },
+
+ payment: {
+ title: '<할인 후 예상 결제 금액>',
+ printMsg: (money) => `${money.toLocaleString()}원\n`,
+ },
+
+ badge: {
+ title: '<12월 이벤트 배지>',
+ printMsg: (badge) => `${badge}`,
+ },
+ },
+
+ // Error
+ errors: {
+ prefix: '[ERROR]',
+ invalidDate: '유효하지 않은 날짜입니다. 다시 입력해 주세요.',
+ invalidOrders: '유효하지 않은 주문입니다. 다시 입력해 주세요.',
+ },
+});
+
+export default MESSAGES; | JavaScript | 밑에서는 `totalBenefitMoney`로 상세하게 메서드명을 지으셔서 이것도 `benefits`보다는 `benefitsDetail`로 좀더 구체적인건 어떨까요? |
@@ -0,0 +1,83 @@
+import deepFreeze from '../utils/deepFreeze.js';
+import { EVENT_MONTH } from './event.js';
+
+const MESSAGES = deepFreeze({
+ // InputView
+ inputs: {
+ getVisitDate: `${EVENT_MONTH}월 중 식당 예상 방문 날짜는 언제인가요? (숫자만 입력해 주세요!)\n`,
+ getOrders:
+ '주문하실 메뉴를 메뉴와 개수를 알려 주세요. (e.g. 해산물파스타-2,레드와인-1,초코케이크-1)\n',
+ },
+
+ // OutputView
+ outputs: {
+ sayHi: `안녕하세요! 우테코 식당 ${EVENT_MONTH}월 이벤트 플래너입니다.`,
+
+ eventPreview: (date) =>
+ `${EVENT_MONTH}월 ${date}일에 우테코 식당에서 받을 이벤트 혜택 미리 보기!\n`,
+
+ menus: {
+ title: '<주문 메뉴>',
+ printMsg: (menus) =>
+ menus.reduce(
+ (acc, { menu, amount }) => `${acc}${menu} ${amount}개\n`,
+ '',
+ ),
+ },
+
+ originalPrice: {
+ title: '<할인 전 총주문 금액>',
+ printMsg: (price) => `${price.toLocaleString()}원\n`,
+ },
+
+ gift: {
+ title: '<증정 메뉴>',
+ printMsg: (gift) => {
+ if (!gift) return '없음\n';
+
+ return `${gift.menu} ${gift.amount}개\n`;
+ },
+ },
+
+ benefits: {
+ title: '<혜택 내역>',
+ printMsg: (benefits) => {
+ if (!benefits) return '없음\n';
+
+ return Object.entries(benefits).reduce(
+ (acc, [eventName, { amount, price }]) =>
+ `${acc}${eventName}: -${(amount * price).toLocaleString()}원\n`,
+ '',
+ );
+ },
+ },
+
+ totalBenefitMoney: {
+ title: '<총혜택 금액>',
+ printMsg: (money) => {
+ if (!money) return '0원\n';
+
+ return `-${money.toLocaleString()}원\n`;
+ },
+ },
+
+ payment: {
+ title: '<할인 후 예상 결제 금액>',
+ printMsg: (money) => `${money.toLocaleString()}원\n`,
+ },
+
+ badge: {
+ title: '<12월 이벤트 배지>',
+ printMsg: (badge) => `${badge}`,
+ },
+ },
+
+ // Error
+ errors: {
+ prefix: '[ERROR]',
+ invalidDate: '유효하지 않은 날짜입니다. 다시 입력해 주세요.',
+ invalidOrders: '유효하지 않은 주문입니다. 다시 입력해 주세요.',
+ },
+});
+
+export default MESSAGES; | JavaScript | 앗 앞에서는 상수값을 가져왔었는데, 이건 하드코딩되어있습니다! 하나로 통일하면 좋을 것 같아요! |
@@ -0,0 +1,63 @@
+import { FRIDAY, SATURDAY, SPECIAL_DATES } from '../constants/calendar.js';
+import { EVENT_PERIOD } from '../constants/event.js';
+import { ALL_EVENTS } from './Events.js';
+
+class EventCalendar {
+ #year;
+
+ #month;
+
+ #date;
+
+ #availableEvents;
+
+ constructor(year, month, date) {
+ this.#year = year;
+ this.#month = month;
+ this.#date = date;
+ this.#availableEvents = {};
+ }
+
+ async setAvailableEvents({ totalPrice, orderCategories }) {
+ const state = this.#getState(totalPrice, orderCategories);
+
+ await Object.values(ALL_EVENTS).forEach((event) => {
+ const { name, getBenefit } = event.getEvent();
+
+ if (event.isEventAvailable(state))
+ this.#availableEvents[name] = getBenefit;
+ });
+ }
+
+ #getState(totalPrice, orderCategories) {
+ return {
+ isWeekend: this.#isWeekend(),
+ isSpecialDate: this.#isSpecialDate(),
+ isChristmasPeriod: this.#isChristmasPeriod(),
+ totalPrice,
+ orderCategories,
+ };
+ }
+
+ #isWeekend() {
+ const dayOfWeek = new Date(
+ `${this.#year}-${this.#month}-${this.#date}`,
+ ).getDay();
+ return dayOfWeek === FRIDAY || dayOfWeek === SATURDAY;
+ }
+
+ #isSpecialDate() {
+ return SPECIAL_DATES.includes(this.#date);
+ }
+
+ #isChristmasPeriod() {
+ const { startDate, endDate } = EVENT_PERIOD;
+ return this.#date >= startDate && this.#date <= endDate;
+ }
+
+ get availableEvents() {
+ return this.#availableEvents;
+ }
+}
+
+export default EventCalendar; | JavaScript | `Period` 꼼꼼하십니다! 👍👍👍 |
@@ -0,0 +1,63 @@
+import { FRIDAY, SATURDAY, SPECIAL_DATES } from '../constants/calendar.js';
+import { EVENT_PERIOD } from '../constants/event.js';
+import { ALL_EVENTS } from './Events.js';
+
+class EventCalendar {
+ #year;
+
+ #month;
+
+ #date;
+
+ #availableEvents;
+
+ constructor(year, month, date) {
+ this.#year = year;
+ this.#month = month;
+ this.#date = date;
+ this.#availableEvents = {};
+ }
+
+ async setAvailableEvents({ totalPrice, orderCategories }) {
+ const state = this.#getState(totalPrice, orderCategories);
+
+ await Object.values(ALL_EVENTS).forEach((event) => {
+ const { name, getBenefit } = event.getEvent();
+
+ if (event.isEventAvailable(state))
+ this.#availableEvents[name] = getBenefit;
+ });
+ }
+
+ #getState(totalPrice, orderCategories) {
+ return {
+ isWeekend: this.#isWeekend(),
+ isSpecialDate: this.#isSpecialDate(),
+ isChristmasPeriod: this.#isChristmasPeriod(),
+ totalPrice,
+ orderCategories,
+ };
+ }
+
+ #isWeekend() {
+ const dayOfWeek = new Date(
+ `${this.#year}-${this.#month}-${this.#date}`,
+ ).getDay();
+ return dayOfWeek === FRIDAY || dayOfWeek === SATURDAY;
+ }
+
+ #isSpecialDate() {
+ return SPECIAL_DATES.includes(this.#date);
+ }
+
+ #isChristmasPeriod() {
+ const { startDate, endDate } = EVENT_PERIOD;
+ return this.#date >= startDate && this.#date <= endDate;
+ }
+
+ get availableEvents() {
+ return this.#availableEvents;
+ }
+}
+
+export default EventCalendar; | JavaScript | new Date(2023,11,25)등으로도 넣을 수 있습니다! 그런데 month의 경우 0으로 시작해서 1빼줘야 하더라구요... |
@@ -0,0 +1,63 @@
+import { FRIDAY, SATURDAY, SPECIAL_DATES } from '../constants/calendar.js';
+import { EVENT_PERIOD } from '../constants/event.js';
+import { ALL_EVENTS } from './Events.js';
+
+class EventCalendar {
+ #year;
+
+ #month;
+
+ #date;
+
+ #availableEvents;
+
+ constructor(year, month, date) {
+ this.#year = year;
+ this.#month = month;
+ this.#date = date;
+ this.#availableEvents = {};
+ }
+
+ async setAvailableEvents({ totalPrice, orderCategories }) {
+ const state = this.#getState(totalPrice, orderCategories);
+
+ await Object.values(ALL_EVENTS).forEach((event) => {
+ const { name, getBenefit } = event.getEvent();
+
+ if (event.isEventAvailable(state))
+ this.#availableEvents[name] = getBenefit;
+ });
+ }
+
+ #getState(totalPrice, orderCategories) {
+ return {
+ isWeekend: this.#isWeekend(),
+ isSpecialDate: this.#isSpecialDate(),
+ isChristmasPeriod: this.#isChristmasPeriod(),
+ totalPrice,
+ orderCategories,
+ };
+ }
+
+ #isWeekend() {
+ const dayOfWeek = new Date(
+ `${this.#year}-${this.#month}-${this.#date}`,
+ ).getDay();
+ return dayOfWeek === FRIDAY || dayOfWeek === SATURDAY;
+ }
+
+ #isSpecialDate() {
+ return SPECIAL_DATES.includes(this.#date);
+ }
+
+ #isChristmasPeriod() {
+ const { startDate, endDate } = EVENT_PERIOD;
+ return this.#date >= startDate && this.#date <= endDate;
+ }
+
+ get availableEvents() {
+ return this.#availableEvents;
+ }
+}
+
+export default EventCalendar; | JavaScript | 원래 반환되는 0,1,2,~ 대신 FRIDAY로 바꾸니까 훨씬 가독성 좋아지네요! 배워갑니다!👍👍👍 |
@@ -0,0 +1,117 @@
+import { EVENT_NAMES } from '../constants/event.js';
+import { DESSERTS, MAIN_COURSES } from '../constants/menus.js';
+
+export const CHRISTMAS_D_DAY = {
+ getBenefit({ date }) {
+ const baseAmount = 1000;
+ const weightAmount = 100;
+
+ return {
+ amount: 1,
+ price: baseAmount + weightAmount * (date - 1),
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.CHRISTMAS_D_DAY,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ isChristmasPeriod }) {
+ return isChristmasPeriod === true;
+ },
+};
+
+export const WEEKDAY = {
+ getBenefit({ orderCntByCategory }) {
+ const discountAmount = 2_023;
+ return {
+ amount: orderCntByCategory[DESSERTS],
+ price: discountAmount,
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.WEEKDAY,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ isWeekend, orderCategories }) {
+ return isWeekend === false && orderCategories.includes(DESSERTS);
+ },
+};
+
+export const WEEKEND = {
+ getBenefit({ orderCntByCategory }) {
+ const discountAmount = 2_023;
+ return {
+ amount: orderCntByCategory[MAIN_COURSES],
+ price: discountAmount,
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.WEEKEND,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ isWeekend, orderCategories }) {
+ return isWeekend === true && orderCategories.includes(MAIN_COURSES);
+ },
+};
+
+export const SPECIAL = {
+ getBenefit() {
+ const discountAmount = 1_000;
+ return {
+ amount: 1,
+ price: discountAmount,
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.SPECIAL,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ isSpecialDate }) {
+ return isSpecialDate === true;
+ },
+};
+
+export const GIFT = {
+ getBenefit() {
+ return {
+ menu: '샴페인',
+ amount: 1,
+ price: 25_000,
+ };
+ },
+
+ getEvent() {
+ return {
+ name: EVENT_NAMES.GIFT,
+ getBenefit: this.getBenefit,
+ };
+ },
+
+ isEventAvailable({ totalPrice }) {
+ return totalPrice >= 120_000;
+ },
+};
+
+export const ALL_EVENTS = Object.freeze({
+ CHRISTMAS_D_DAY,
+ WEEKDAY,
+ WEEKEND,
+ SPECIAL,
+ GIFT,
+}); | JavaScript | 1_000, 1000 중에 하나로 통일하면 좋을 것 같아요! |
@@ -0,0 +1,94 @@
+import OrderItem from './OrderItem.js';
+
+import MESSAGES from '../constants/messages.js';
+
+import throwError from '../utils/throwError.js';
+import {
+ hasDuplicatedMenu,
+ hasOnlyBeverages,
+ isTotalAmountOfMenusValid,
+} from '../utils/validators.js';
+
+class Receipt {
+ #orders;
+
+ #orderItems;
+
+ constructor(orders) {
+ this.#validate(orders);
+ this.#orders = orders;
+ this.#orderItems = [];
+ }
+
+ #validate(orders) {
+ if (!isTotalAmountOfMenusValid(orders))
+ throwError(MESSAGES.errors.invalidOrders);
+
+ if (hasDuplicatedMenu(orders)) throwError(MESSAGES.errors.invalidOrders);
+
+ if (hasOnlyBeverages(orders)) throwError(MESSAGES.errors.invalidOrders);
+ }
+
+ generateOrders() {
+ this.#orderItems = this.#orders.map(
+ ({ menu, amount }) => new OrderItem(menu, amount),
+ );
+ }
+
+ get totalPrice() {
+ return this.#orderItems.reduce(
+ (totalPrice, orderItem) => totalPrice + orderItem.totalPrice,
+ 0,
+ );
+ }
+
+ get receipt() {
+ const receipt = {};
+
+ this.#orderItems.forEach((orderItem) => {
+ const { category, menu, amount } = orderItem.item;
+
+ if (!Array.isArray(receipt[category])) {
+ receipt[category] = [];
+ }
+
+ receipt[category].push({ menu, amount });
+ });
+
+ return receipt;
+ }
+
+ get orderCategories() {
+ const categories = new Set();
+
+ this.#orderItems.forEach((orderItem) => {
+ const { category } = orderItem.item;
+ categories.add(category);
+ });
+
+ return [...categories];
+ }
+
+ get orderCntByCategory() {
+ const orderCnt = {};
+
+ this.#orderItems.forEach((orderItem) => {
+ const { category, amount } = orderItem.item;
+
+ if (!orderCnt[category]) orderCnt[category] = 0;
+
+ orderCnt[category] += amount;
+ });
+
+ return orderCnt;
+ }
+
+ get menus() {
+ return this.#orderItems.map((orderItem) => {
+ const { menu, amount } = orderItem.item;
+ return { menu, amount };
+ });
+ }
+}
+
+export default Receipt; | JavaScript | 혹시 여기 공백이 있는 이유가 있을까요?? |
@@ -0,0 +1,94 @@
+import OrderItem from './OrderItem.js';
+
+import MESSAGES from '../constants/messages.js';
+
+import throwError from '../utils/throwError.js';
+import {
+ hasDuplicatedMenu,
+ hasOnlyBeverages,
+ isTotalAmountOfMenusValid,
+} from '../utils/validators.js';
+
+class Receipt {
+ #orders;
+
+ #orderItems;
+
+ constructor(orders) {
+ this.#validate(orders);
+ this.#orders = orders;
+ this.#orderItems = [];
+ }
+
+ #validate(orders) {
+ if (!isTotalAmountOfMenusValid(orders))
+ throwError(MESSAGES.errors.invalidOrders);
+
+ if (hasDuplicatedMenu(orders)) throwError(MESSAGES.errors.invalidOrders);
+
+ if (hasOnlyBeverages(orders)) throwError(MESSAGES.errors.invalidOrders);
+ }
+
+ generateOrders() {
+ this.#orderItems = this.#orders.map(
+ ({ menu, amount }) => new OrderItem(menu, amount),
+ );
+ }
+
+ get totalPrice() {
+ return this.#orderItems.reduce(
+ (totalPrice, orderItem) => totalPrice + orderItem.totalPrice,
+ 0,
+ );
+ }
+
+ get receipt() {
+ const receipt = {};
+
+ this.#orderItems.forEach((orderItem) => {
+ const { category, menu, amount } = orderItem.item;
+
+ if (!Array.isArray(receipt[category])) {
+ receipt[category] = [];
+ }
+
+ receipt[category].push({ menu, amount });
+ });
+
+ return receipt;
+ }
+
+ get orderCategories() {
+ const categories = new Set();
+
+ this.#orderItems.forEach((orderItem) => {
+ const { category } = orderItem.item;
+ categories.add(category);
+ });
+
+ return [...categories];
+ }
+
+ get orderCntByCategory() {
+ const orderCnt = {};
+
+ this.#orderItems.forEach((orderItem) => {
+ const { category, amount } = orderItem.item;
+
+ if (!orderCnt[category]) orderCnt[category] = 0;
+
+ orderCnt[category] += amount;
+ });
+
+ return orderCnt;
+ }
+
+ get menus() {
+ return this.#orderItems.map((orderItem) => {
+ const { menu, amount } = orderItem.item;
+ return { menu, amount };
+ });
+ }
+}
+
+export default Receipt; | JavaScript | 구조분해 할당 잘 쓰십니당! 👍 |
@@ -0,0 +1,144 @@
+import EventCalendar from '../domain/EventCalendar.js';
+import Receipt from '../domain/Receipt.js';
+
+import {
+ EVENT_MONTH,
+ EVENT_NAMES,
+ EVENT_PERIOD,
+ EVENT_YEAR,
+} from '../constants/event.js';
+import MESSAGES from '../constants/messages.js';
+
+import { isInteger, isNumberInRange } from '../utils/validators.js';
+import throwError from '../utils/throwError.js';
+import { isEmptyObject } from '../utils/object.js';
+
+class EventPlanner {
+ #visitDate;
+
+ #eventCalendar;
+
+ #receipt;
+
+ #benefits;
+
+ constructor(date) {
+ this.#validate(date);
+ this.#visitDate = date;
+ this.#eventCalendar = new EventCalendar(EVENT_YEAR, EVENT_MONTH, date);
+ this.#benefits = {};
+ }
+
+ #validate(date) {
+ const { startDate, endDate } = EVENT_PERIOD;
+
+ if (!isNumberInRange(startDate, endDate, date))
+ throwError(MESSAGES.errors.invalidDate);
+
+ if (!isInteger(date)) throwError(MESSAGES.errors.invalidDate);
+ }
+
+ generateReceipt(orders) {
+ this.#receipt = new Receipt(orders);
+ this.#receipt.generateOrders(orders);
+ }
+
+ generateBenefits() {
+ const { totalPrice, orderCategories } = this.#receipt;
+
+ this.#eventCalendar.setAvailableEvents({
+ totalPrice,
+ orderCategories,
+ });
+
+ this.#setBenefits();
+ }
+
+ #setBenefits() {
+ if (this.originalPrice < 10_000) return;
+
+ const conditions = {
+ orderCntByCategory: this.#receipt.orderCntByCategory,
+ date: this.#visitDate,
+ };
+
+ Object.entries(this.#eventCalendar.availableEvents).forEach(
+ ([eventName, getBenefit]) => {
+ this.#benefits[eventName] = getBenefit(conditions);
+ },
+ );
+ }
+
+ #getBadge() {
+ const money = this.totalBenefitMoney;
+
+ if (money >= 20_000) return '산타';
+
+ if (money >= 10_000) return '트리';
+
+ if (money >= 5000) return '별';
+
+ return '없음';
+ }
+
+ get visitDate() {
+ return this.#visitDate;
+ }
+
+ // 주문 메뉴
+ get menus() {
+ return this.#receipt.menus;
+ }
+
+ // 할인 전 총주문 금액
+ get originalPrice() {
+ return this.#receipt.totalPrice;
+ }
+
+ // 증정 메뉴
+ get gift() {
+ if (isEmptyObject(this.#benefits)) return null;
+
+ return this.#benefits[EVENT_NAMES.GIFT];
+ }
+
+ // 혜택 내역
+ get benefits() {
+ if (isEmptyObject(this.#benefits)) return null;
+
+ return this.#benefits;
+ }
+
+ // 총 혜택 금액
+ get totalBenefitMoney() {
+ if (isEmptyObject(this.#benefits)) return 0;
+
+ return Object.values(this.#benefits).reduce(
+ (totalBenefitMoney, { amount, price }) =>
+ totalBenefitMoney + amount * price,
+ 0,
+ );
+ }
+
+ // 할인 후 예상 결제 금액
+ get payment() {
+ if (isEmptyObject(this.#benefits)) return this.originalPrice;
+
+ const discountAmount = Object.entries(this.#benefits).reduce(
+ (payment, [eventName, { amount, price }]) => {
+ if (eventName !== EVENT_NAMES.GIFT) return payment + amount * price;
+ return payment;
+ },
+ 0,
+ );
+
+ return this.originalPrice - discountAmount;
+ }
+
+ // 12월 이벤트 배지
+ get badge() {
+ return this.#getBadge();
+ }
+}
+
+export default EventPlanner; | JavaScript | 해당 부분은 따로 객체로 관리해도 좋을 것 같아요! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.