code stringlengths 41 34.3k | lang stringclasses 8
values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,45 @@
+package christmas.domain.event.discount;
+
+import java.util.List;
+
+import christmas.domain.date.Date;
+import christmas.domain.date.DayOfWeek;
+
+import christmas.domain.reward.DiscountEventReward;
+import christmas.domain.menu.Category;
+
+import christmas.domain.order.Bill;
+import christmas.domain.order.OrderInfo;
+import christmas.lib.event.DiscountEvent;
+
+import static christmas.constant.EventConstant.WEEKDAY_DISCOUNT_EVENT_MESSAGE;
+import static christmas.constant.EventConstant.WEEKDAY_DISCOUNT_PRICE;
+
+public class WeekdayDiscountEvent extends DiscountEvent<Bill> {
+ private final Integer DISCOUNT_PRICE = WEEKDAY_DISCOUNT_PRICE;
+ private final String EVENT_NAME = WEEKDAY_DISCOUNT_EVENT_MESSAGE;
+
+ @Override
+ public boolean checkCondition(Date date) {
+ DayOfWeek dayOfWeek = date.dayOfWeek();
+ if (dayOfWeek.isWeekday()) {
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public DiscountEventReward provideReward(Bill bill) {
+ List<OrderInfo> orderInfos = bill.orderDetail().get(Category.DESERT);
+ Integer count = countOrderMenu(orderInfos);
+ return new DiscountEventReward(EVENT_NAME, count * DISCOUNT_PRICE);
+ }
+
+ private int countOrderMenu(List<OrderInfo> orderInfos) {
+ int count = 0;
+ for (OrderInfo orderInfo : orderInfos) {
+ count += orderInfo.amount();
+ }
+ return count;
+ }
+} | Java | ์ด ๋ถ๋ถ์ stream ์ ์ฌ์ฉํด ์ด๋ ๊ฒ ๊ตฌํํ ์๋ ์์ต๋๋ค ๐
```java
public class WeekdayDiscountEvent extends DiscountEvent<Bill> {
//...
private int countOrderMenu(List<OrderInfo> orderInfos) {
return orderInfos.stream()
.mapToInt.(OrderInfo::amount)
.sum();
}
//...
}
``` |
@@ -0,0 +1,96 @@
+package christmas.domain.order;
+
+import java.util.ArrayList;
+import java.util.EnumMap;
+import java.util.List;
+
+import christmas.domain.menu.Category;
+import christmas.exception.OrderException;
+import christmas.exception.message.OrderExceptionMessage;
+
+import static christmas.constant.OrderConstant.MAX_TOTAL_ORDER_COUNT;
+
+public record Bill(int totalPrice, EnumMap<Category, List<OrderInfo>> orderDetail) {
+ public static Bill of(List<RequestOrder> requestOrderList) {
+ EnumMap<Category, List<OrderInfo>> orderMenuBoard = confirmOrders(requestOrderList);
+
+ validate(orderMenuBoard);
+
+ int totalPrice = calculateTotalPrice(orderMenuBoard);
+ return new Bill(totalPrice, orderMenuBoard);
+ }
+
+ private static EnumMap<Category, List<OrderInfo>> confirmOrders(List<RequestOrder> requestOrderList) {
+ EnumMap<Category, List<OrderInfo>> orderMenuBoard = initOrderMenuBoard();
+
+ for (RequestOrder requestOrder : requestOrderList) {
+ confirmOrder(requestOrder, orderMenuBoard);
+ }
+ return orderMenuBoard;
+ }
+
+ private static void confirmOrder(RequestOrder requestOrder, EnumMap<Category, List<OrderInfo>> orderMenuBoard) {
+ String orderName = requestOrder.orderName();
+ int orderAmount = requestOrder.amount();
+
+ OrderResult orderResult = OrderResult.of(orderName, orderAmount);
+ orderMenuBoard.get(orderResult.category()).add(orderResult.orderInfo());
+ }
+
+
+ private static EnumMap<Category, List<OrderInfo>> initOrderMenuBoard() {
+ EnumMap<Category, List<OrderInfo>> orderMenuBoard = new EnumMap<>(Category.class);
+
+ for (Category category : Category.values()) {
+ orderMenuBoard.put(category, new ArrayList<>());
+ }
+ return orderMenuBoard;
+ }
+
+ private static void validate(EnumMap<Category, List<OrderInfo>> orderMenuBoard) {
+ int totalAmount = countTotalOrderMenu(orderMenuBoard);
+ validateTotalAmountInRange(totalAmount);
+ validateMenuIsOnlyDrink(orderMenuBoard.get(Category.DRINK), totalAmount);
+ }
+
+ private static void validateTotalAmountInRange(int totalAmount) {
+ if (totalAmount > MAX_TOTAL_ORDER_COUNT) {
+ throw new OrderException(OrderExceptionMessage.OVERALL_ORDER_COUNT);
+ }
+ }
+
+ private static void validateMenuIsOnlyDrink(List<OrderInfo> orderDrinks, int totalOrderCount) {
+ int drinkOrderCount = countOrderMenus(orderDrinks);
+ if (drinkOrderCount == totalOrderCount) {
+ throw new OrderException(OrderExceptionMessage.ONLY_DRINK);
+ }
+ }
+
+
+ private static Integer countTotalOrderMenu(EnumMap<Category, List<OrderInfo>> orderBoard) {
+ int totalOrderCount = 0;
+ for (List<OrderInfo> orderInfos : orderBoard.values()) {
+ totalOrderCount += countOrderMenus(orderInfos);
+ }
+ return totalOrderCount;
+ }
+
+ private static Integer countOrderMenus(List<OrderInfo> orderInfos) {
+ int orderCount = 0;
+ for (OrderInfo orderInfo : orderInfos) {
+ orderCount += orderInfo.amount();
+ }
+ return orderCount;
+ }
+
+ private static Integer calculateTotalPrice(EnumMap<Category, List<OrderInfo>> orderBoard) {
+ int totalPrice = 0;
+ for (List<OrderInfo> orderInfos : orderBoard.values()) {
+ for (OrderInfo orderInfo : orderInfos) {
+ int price = orderInfo.menu().price();
+ totalPrice += orderInfo.amount() * price;
+ }
+ }
+ return totalPrice;
+ }
+}
\ No newline at end of file | Java | ์ ๋ ๊ฒ์ฆ๋ก์ง์ ๋ถ๋ฆฌํ๋๊ฒ์ ์ ํธํ๋๋ฐ ์ด ๋ถ๋ถ์ ๋ํด์ ์ด๋ป๊ฒ ์๊ฐํ์๋์ง ๊ถ๊ธํฉ๋๋ค! |
@@ -0,0 +1,55 @@
+package christmas.controller;
+
+import christmas.domain.date.Date;
+import christmas.domain.badge.Badge;
+import christmas.domain.reward.Reward;
+import christmas.domain.order.Bill;
+import christmas.dto.RewardDto;
+import christmas.factory.ControllerFactory;
+import christmas.view.OutputView;
+
+public class GameController {
+ private final DateController dateController = ControllerFactory.getDateController();
+ private final OrderController orderController = ControllerFactory.getOrderController();
+ private final EventController eventController = ControllerFactory.getEventController();
+ private final BadgeController badgeController = ControllerFactory.getBadgeController();
+
+ public void run() {
+ printWelcomeMessage();
+
+ Date date = dateController.acceptVisitDate();
+ Bill bill = orderController.acceptOrder();
+ printOrderResult(date, bill);
+
+ Reward reward = eventController.confirmReward(date, bill);
+ RewardDto rewardDto = reward.toDto();
+
+ printRewardResult(rewardDto);
+ printFinalCheckoutPrice(bill, rewardDto);
+
+ printBadgeResult(badgeController.grantBadge(rewardDto));
+ }
+
+ public void printWelcomeMessage() {
+ OutputView.printWelcomeMessage();
+ }
+
+ public void printOrderResult(Date date, Bill bill) {
+ OutputView.printPreviewMessage(date);
+ OutputView.printOrderMessage(bill);
+ }
+
+ public void printFinalCheckoutPrice(Bill bill, RewardDto rewardDto) {
+
+ int checkoutPrice = bill.totalPrice() - rewardDto.getTotalDiscountReward();
+ OutputView.printFinalCheckoutPriceMessage(checkoutPrice);
+ }
+
+ public void printRewardResult(RewardDto rewardDto) {
+ OutputView.printRewardsMessage(rewardDto);
+ }
+
+ public void printBadgeResult(Badge badge) {
+ OutputView.printBadgeMessage(badge);
+ }
+} | Java | ์๊ตฌ์ฌํญ์ ์๊ฐํด์ ,
์์ฑํ๊ณ ๊ฐ์ด ์ถ๋ ฅํ๋ ์์ผ๋ก ์๊ฐํ๋๋ฐ ,
์ด๋ ๊ฒ print ๊ตฌ๋ฌธ ๋ชจ์๋์๊ฑฐ๋ ๊ด์ฐฎ๋ค์!! |
@@ -0,0 +1,32 @@
+package christmas.domain.date;
+
+import christmas.exception.DateException;
+import christmas.exception.message.DateExceptionMessage;
+import christmas.util.Calendar;
+
+import static christmas.constant.DateConstant.START_DAY;
+import static christmas.constant.DateConstant.END_DAY;
+
+public record Date(int day, DayOfWeek dayOfWeek) {
+ public static Date of(int day) {
+ validate(day);
+
+ DayOfWeek dayOfWeek = getDayOfWeek(day);
+ return new Date(day, dayOfWeek);
+ }
+
+ private static void validate(int day) {
+ validateDayRange(day);
+ }
+
+ private static void validateDayRange(int day) {
+ if (day < START_DAY || day > END_DAY) {
+ throw new DateException(DateExceptionMessage.INVALID_DAY);
+ }
+ }
+
+ private static DayOfWeek getDayOfWeek(int day) {
+ return Calendar.calculateDayOfWeek(day);
+ }
+
+} | Java | ์ ๋ ๋ณด๊ณ ์ ๊ธฐํด์ ๋๋ฌ์ต๋๋ค.. |
@@ -0,0 +1,37 @@
+package christmas.domain.event.discount;
+
+import christmas.domain.date.Date;
+import christmas.domain.reward.DiscountEventReward;
+import christmas.lib.event.DiscountEvent;
+
+import static christmas.constant.EventConstant.CHRISTMAS_DAY;
+import static christmas.constant.EventConstant.D_DAY_DISCOUNT_UNIT;
+import static christmas.constant.EventConstant.CHRISTMAS_EVENT_MESSAGE;
+import static christmas.constant.EventConstant.D_DAY_START_PRICE;
+
+
+public class ChristmasDiscountEvent extends DiscountEvent<Date> {
+ private final Integer D_DAY = CHRISTMAS_DAY;
+ private final Integer START_PRICE = D_DAY_START_PRICE;
+ private final Integer DISCOUNT_UNIT = D_DAY_DISCOUNT_UNIT;
+ private final String EVENT_NAME = CHRISTMAS_EVENT_MESSAGE;
+
+ @Override
+ public boolean checkCondition(Date date) {
+ if (date.day() <= D_DAY) {
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public DiscountEventReward provideReward(Date date) {
+ int currentDay = date.day();
+ int discountPrice = calculateDiscountPrice(currentDay);
+ return new DiscountEventReward(EVENT_NAME, discountPrice);
+ }
+
+ private Integer calculateDiscountPrice(int currentDay) {
+ return START_PRICE + (currentDay - 1) * DISCOUNT_UNIT;
+ }
+} | Java | ์๋ ์ ๋ ฌ์ด , ๋ฐ์ผ๋ก ๋ด๋ ค๊ฐ์ ๋ณ๊ฒฝํ๋ค๊ณ ์ ๊ฒฝ์ผ๋๋ฐ
ํด๋น ๋ถ๋ถ์ ๋์ณค๋ค์ ใ
ใ
|
@@ -0,0 +1,14 @@
+package christmas.controller;
+
+import christmas.domain.badge.Badge;
+import christmas.dto.RewardDto;
+import christmas.factory.ServiceFactory;
+import christmas.service.BadgeService;
+
+public class BadgeController {
+ private BadgeService badgeService = ServiceFactory.getBadgeService();
+
+ public Badge grantBadge(RewardDto rewardDto) {
+ return this.badgeService.createBadge(rewardDto.totalRewardPrice());
+ }
+} | Java | grantBadge! ํด๋์ค๋ช
์์ ์ผ์ค๊ฐ ๋์น๋ค์ ใ
ใ
๊ทธ๋ฐ๋ฐ ํน์ get ๋์ ์ grant๋ฅผ ๋ฉ์๋๋ช
์ผ๋ก ์ ์ธํ ์ด์ ๊ฐ ์์๊น์? |
@@ -0,0 +1,106 @@
+package chess.database.dao;
+
+import chess.dto.game.ChessGameLoadDto;
+import chess.dto.game.ChessGameSaveDto;
+
+import java.sql.*;
+import java.util.ArrayList;
+import java.util.List;
+
+public final class DbChessGameDao implements ChessDao {
+
+ private final String url;
+ private final String user;
+ private final String password;
+
+ public DbChessGameDao(final String url, final String user, final String password) {
+ this.url = url;
+ this.user = user;
+ this.password = password;
+ }
+
+ private Connection getConnection() {
+ try {
+ return DriverManager.getConnection(url, user, password);
+ } catch (SQLException e) {
+// throw new RuntimeException(e);
+ return null;
+ }
+ }
+
+ @Override
+ public void save(final ChessGameSaveDto dto) {
+ final String sql = "INSERT INTO chess_game(piece_type, piece_file, piece_rank, piece_team, last_turn) VALUES (?, ?, ?, ?, ?)";
+ try (final Connection connection = getConnection();
+ final PreparedStatement preparedStatement = connection.prepareStatement(sql);
+ ) {
+ for (int i = 0; i < dto.getSize(); i++) {
+ preparedStatement.setString(1, dto.getPieceTypes().get(i));
+ preparedStatement.setString(2, dto.getPieceFiles().get(i));
+ preparedStatement.setString(3, dto.getPieceRanks().get(i));
+ preparedStatement.setString(4, dto.getPieceTeams().get(i));
+ preparedStatement.setString(5, dto.getLastTurns().get(i));
+ preparedStatement.executeUpdate();
+ }
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ } catch (NullPointerException ignored) {
+ }
+ }
+
+ @Override
+ public ChessGameLoadDto loadGame() {
+ final String sql = "SELECT piece_type, piece_file, piece_rank, piece_team, last_turn FROM chess_game";
+ try (final Connection connection = getConnection();
+ final PreparedStatement preparedStatement = connection.prepareStatement(sql);
+ final ResultSet resultSet = preparedStatement.executeQuery();
+ ) {
+ final List<String> pieceType = new ArrayList<>();
+ final List<String> pieceFile = new ArrayList<>();
+ final List<String> pieceRanks = new ArrayList<>();
+ final List<String> pieceTeams = new ArrayList<>();
+ String lastTurn = "";
+
+ while (resultSet.next()) {
+ pieceType.add(resultSet.getString("piece_type"));
+ pieceFile.add(resultSet.getString("piece_file"));
+ pieceRanks.add(resultSet.getString("piece_rank"));
+ pieceTeams.add(resultSet.getString("piece_team"));
+ lastTurn = resultSet.getString("last_turn");
+ }
+ return new ChessGameLoadDto(pieceType, pieceFile, pieceRanks, pieceTeams, lastTurn);
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ } catch (NullPointerException e) {
+ return null;
+ }
+ }
+
+ @Override
+ public boolean hasHistory() {
+ final String sql = "SELECT piece_type, piece_file, piece_rank, piece_team, last_turn FROM chess_game";
+ try (final Connection connection = getConnection();
+ final PreparedStatement preparedStatement = connection.prepareStatement(sql);
+ final ResultSet resultSet = preparedStatement.executeQuery();
+ ) {
+ return resultSet.next();
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ } catch (NullPointerException e) {
+ return false;
+ }
+ }
+
+ @Override
+ public void delete() {
+ final String sql = "DELETE FROM chess_game";
+ try (final Connection connection = getConnection();
+ final PreparedStatement preparedStatement = connection.prepareStatement(sql)
+ ) {
+ preparedStatement.executeUpdate();
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ } catch (NullPointerException ignored) {
+ }
+ }
+} | Java | Jdbc Connection ๊ด๋ฆฌ๋ฅผ Dao์์ ํด์ฃผ๊ณ ๊ณ์๋ค์! ๊ทธ๋ฐ๋ฐ ๊ด๋ฆฌํด์ผ ํ ํ
์ด๋ธ์ด ๋์ด๋์ ์ฌ๋ฌ Dao ๊ฐ์ฒด๊ฐ ์๊ฒจ๋๊ฒ ๋๋ฉด ์ค๋ณต๋๋ ์ฝ๋์ธ ์ธ์คํด์ค ๋ณ์๋ค์ด ๋ฐ์ํ๊ฒ ๋ ๊ฒ ๊ฐ์์.
์ ๋ ์ฒด์ค๋ฏธ์
์ ์งํํ๋ฉฐ ๋ฆฌ๋ทฐ์ด๋ถ๊ป ๋ฆฌ๋ทฐ๋ฐ์ ์ฌํญ์ธ๋ฐ DB Connection๊ณผ ๊ฐ์ resource ๊ด๋ฆฌ ์ฝ๋๋ฅผ Util ํด๋์ค ๋ฑ์ผ๋ก ๊ตฌ๋ถํด์ ๊ด๋ฆฌํด๋ณด์๋ ๊ฑด ์ด๋จ์ง ์ ์๋๋ ค๋ด
๋๋ค! |
@@ -0,0 +1,106 @@
+package chess.database.dao;
+
+import chess.dto.game.ChessGameLoadDto;
+import chess.dto.game.ChessGameSaveDto;
+
+import java.sql.*;
+import java.util.ArrayList;
+import java.util.List;
+
+public final class DbChessGameDao implements ChessDao {
+
+ private final String url;
+ private final String user;
+ private final String password;
+
+ public DbChessGameDao(final String url, final String user, final String password) {
+ this.url = url;
+ this.user = user;
+ this.password = password;
+ }
+
+ private Connection getConnection() {
+ try {
+ return DriverManager.getConnection(url, user, password);
+ } catch (SQLException e) {
+// throw new RuntimeException(e);
+ return null;
+ }
+ }
+
+ @Override
+ public void save(final ChessGameSaveDto dto) {
+ final String sql = "INSERT INTO chess_game(piece_type, piece_file, piece_rank, piece_team, last_turn) VALUES (?, ?, ?, ?, ?)";
+ try (final Connection connection = getConnection();
+ final PreparedStatement preparedStatement = connection.prepareStatement(sql);
+ ) {
+ for (int i = 0; i < dto.getSize(); i++) {
+ preparedStatement.setString(1, dto.getPieceTypes().get(i));
+ preparedStatement.setString(2, dto.getPieceFiles().get(i));
+ preparedStatement.setString(3, dto.getPieceRanks().get(i));
+ preparedStatement.setString(4, dto.getPieceTeams().get(i));
+ preparedStatement.setString(5, dto.getLastTurns().get(i));
+ preparedStatement.executeUpdate();
+ }
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ } catch (NullPointerException ignored) {
+ }
+ }
+
+ @Override
+ public ChessGameLoadDto loadGame() {
+ final String sql = "SELECT piece_type, piece_file, piece_rank, piece_team, last_turn FROM chess_game";
+ try (final Connection connection = getConnection();
+ final PreparedStatement preparedStatement = connection.prepareStatement(sql);
+ final ResultSet resultSet = preparedStatement.executeQuery();
+ ) {
+ final List<String> pieceType = new ArrayList<>();
+ final List<String> pieceFile = new ArrayList<>();
+ final List<String> pieceRanks = new ArrayList<>();
+ final List<String> pieceTeams = new ArrayList<>();
+ String lastTurn = "";
+
+ while (resultSet.next()) {
+ pieceType.add(resultSet.getString("piece_type"));
+ pieceFile.add(resultSet.getString("piece_file"));
+ pieceRanks.add(resultSet.getString("piece_rank"));
+ pieceTeams.add(resultSet.getString("piece_team"));
+ lastTurn = resultSet.getString("last_turn");
+ }
+ return new ChessGameLoadDto(pieceType, pieceFile, pieceRanks, pieceTeams, lastTurn);
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ } catch (NullPointerException e) {
+ return null;
+ }
+ }
+
+ @Override
+ public boolean hasHistory() {
+ final String sql = "SELECT piece_type, piece_file, piece_rank, piece_team, last_turn FROM chess_game";
+ try (final Connection connection = getConnection();
+ final PreparedStatement preparedStatement = connection.prepareStatement(sql);
+ final ResultSet resultSet = preparedStatement.executeQuery();
+ ) {
+ return resultSet.next();
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ } catch (NullPointerException e) {
+ return false;
+ }
+ }
+
+ @Override
+ public void delete() {
+ final String sql = "DELETE FROM chess_game";
+ try (final Connection connection = getConnection();
+ final PreparedStatement preparedStatement = connection.prepareStatement(sql)
+ ) {
+ preparedStatement.executeUpdate();
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ } catch (NullPointerException ignored) {
+ }
+ }
+} | Java | Dao์์ NullPointerException์ ๋ฌด์ํ๋ ๊ฒ์ ๋ฆฌ๋ทฐ์ด๋ฅผ ์ํ ๋ฐฐ๋ ค์ผ๊น์? ใ
ใ
๊ทธ๊ฒ ์๋๋ผ๋ฉด ์ด๋ค ์๋๋ก ์์ธ๋ฅผ ๋ฌด์์ฒ๋ฆฌํด์ฃผ์ ๊ฑด์ง ๊ถ๊ธํฉ๋๋ค~ |
@@ -1,7 +1,97 @@
-# java-chess
+## ์ ์ฒด ์๋๋ฆฌ์ค
-์ฒด์ค ๋ฏธ์
์ ์ฅ์
+1. start๋ฅผ ์
๋ ฅ ๋ฐ์ผ๋ฉด ๊ฒ์์ ์์ํ๋ค.
+ - [์์ธ] ๊ฒ์์ด ์์ํ์ง ์์๋๋ฐ move๋ฅผ ์
๋ ฅํ๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.
+2. move sourcePosition targetPosition์ ์
๋ ฅ ๋ฐ์ ๊ธฐ๋ฌผ์ ์์ง์ธ๋ค.
+ - [์์ธ] ๊ฒ์ ์งํ ์ค์ start๋ฅผ ์
๋ ฅํ๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.
+3. status๋ฅผ ์
๋ ฅ ๋ฐ์ ๊ฐ ์ง์์ score๋ฅผ ์ถ๋ ฅํ๊ณ ์นํจ๋ฅผ ์ถ๋ ฅํ๋ค.
+4. ํน์ด ๋จผ์ ์กํ๋ ์ง์์ด ํจํ๊ณ , ์ฆ์ ๊ฒ์์ ์ข
๋ฃํ๋ค.
+5. end๋ฅผ ์
๋ ฅ ๋ฐ์ ๊ฒ์์ ์ข
๋ฃํ๋ค.
-## ์ฐ์ํํ
ํฌ์ฝ์ค ์ฝ๋๋ฆฌ๋ทฐ
+### ์ฒด์ค ๊ฒ์(ChessGame)
-- [์จ๋ผ์ธ ์ฝ๋ ๋ฆฌ๋ทฐ ๊ณผ์ ](https://github.com/woowacourse/woowacourse-docs/blob/master/maincourse/README.md)
+- [x] ์ฒด์ค ๊ฒ์์
+ - [x] ์์น์ ๋ฐ๋ฅธ ๊ธฐ๋ฌผ ์ ๋ณด๋ฅผ ๊ฐ์ง๊ณ ์๋ค.
+ - [x] ํ์ฌ ์ด๋ ์ง์์ ํด์ธ์ง ๊ฐ์ง๊ณ ์๋ค.
+ - [x] ๊ฐ ์ง์์ ์ ์๋ฅผ ๊ณ์ฐํ ์ ์๋ค.
+ - [x] ์์ด ์ฃฝ์ผ๋ฉด ๊ฒ์์ด ๋๋๋ค.
+ - [x] ์ด๋ค ์ง์์ด ์ด๊ฒผ๋์ง ์ถ๋ ฅํ๊ณ ๊ฒ์์ ๋๋ธ๋ค.
+
+## ๊ธฐ๋ฌผ(Piece)
+
+- [x] ๊ธฐ๋ฌผ์
+ - [x] ๊ธฐ๋ฌผ์ ํ์
(PieceType)๊ณผ ์ง์(Team), ์ด๋ ์ ๋ต(MovingStrategies)์ ๊ฐ์ง๊ณ ์๋ค.
+ - [x] ๊ฐ๊ฐ์ ๊ณ ์ ํ์
์ผ๋ก ๊ตฌ๋ถ๋๋ค.
+ - [x] ์์ง์ด๋ คํ ๊ธฐ๋ฌผ์ด ์ด๊ธฐ ํฐ์ด๋ผ๋ฉด ์ผ๋ฐ ํฐ์ผ๋ก ๋ฐ๊ฟ์ค๋ค.
+ - [์์ธ] ํ๋ง๋ฒ์ ์์ง์ด์ง ๋ชปํ๋ ๊ณณ์ผ๋ก ์ด๋ํ๋ ค๊ณ ํ๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.
+ - [์์ธ] ์ด๋ํ๊ณ ์ ํ๋ ์ง์ ์ ์๊ตฐ ๊ธฐ๋ฌผ์ด ์์ผ๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.
+ - [์์ธ] ๋น ๊ธฐ๋ฌผ(EMPTY)๋ฅผ ์์ง์ด๋ ค ํ๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.
+
+### ์ฌ๋ผ์ด๋ฉ ๊ฐ๋ฅํ ๊ธฐ๋ฌผ (SlidingPiece)
+
+- [x] ๋ฃฉ(Rook)
+ - [x] ์, ํ, ์ข, ์ฐ๋ก ์์ง์ผ ์ ์๋ค.
+- [x] ๋น์(Bishop)
+ - [x] ๋๊ฐ์ ์ผ๋ก ์์ง์ผ ์ ์๋ค.
+- [x] ํธ(Queen)
+ - [x] ์, ํ, ์ข, ์ฐ, ๋๊ฐ์ ์ผ๋ก ์์ง์ผ ์ ์๋ค.
+
+### ์ฌ๋ผ์ด๋ฉ ๋ถ๊ฐํ ๊ธฐ๋ฌผ (NonSlidingPiece)
+
+- [x] ๋์ดํธ(Knight)
+ - [x] ๋์ดํธ ๊ณ ์ ์ ์ฌ๋ ๋ฐฉํฅ์ผ๋ก ์์ง์ผ ์ ์๋ค.
+- [x] ํน(King)
+ - [x] ์, ํ, ์ข, ์ฐ๋ก ์์ง์ผ ์ ์๋ค.
+
+### Empty
+
+- [x] ๋น ๊ธฐ๋ฌผ์ ๋ปํ๊ณ , ์์ง์ผ ์ ์๋ค.
+
+### ํฐ(Pawn)
+
+- [x] InitialWhitePawn
+ - [x] ์ด๋ ์ ๋ต : ์๋ก ๋ ์นธ, ์๋ก ํ ์นธ ์์ง์ผ ์ ์๋ค.
+ - [x] ๊ณต๊ฒฉ ์ ๋ต : ์ผ์ชฝ ์, ์ค๋ฅธ์ชฝ ์๋ก ํ ์นธ ์์ง์ผ ์ ์๋ค.
+- [x] InitialBlackPawn
+ - [x] ์ด๋ ์ ๋ต : ์๋๋ก ๋ ์นธ, ์๋๋ก ํ ์นธ ์์ง์ผ ์ ์๋ค.
+ - [x] ๊ณต๊ฒฉ ์ ๋ต : ์ผ์ชฝ ์๋, ์ค๋ฅธ์ชฝ ์๋๋ก ํ ์นธ ์์ง์ผ ์ ์๋ค.
+- [x] WhitePawn
+ - [x] ์ด๋ ์ ๋ต : ์๋ก ํ ์นธ ์์ง์ผ ์ ์๋ค.
+ - [x] ๊ณต๊ฒฉ ์ ๋ต : ์ผ์ชฝ ์, ์ค๋ฅธ์ชฝ ์๋ก ํ ์นธ ์์ง์ผ ์ ์๋ค.
+- [x] BlackPawn
+ - [x] ์ด๋ ์ ๋ต : ์๋๋ก ํ ์นธ ์์ง์ผ ์ ์๋ค.
+ - [x] ๊ณต๊ฒฉ ์ ๋ต : ์ผ์ชฝ ์๋, ์ค๋ฅธ์ชฝ ์๋๋ก ํ ์นธ ์์ง์ผ ์ ์๋ค.
+
+### Turn
+
+- [x] ์ด๊ธฐ ํด์ WHITE๋ถํฐ ์์๋๋ค.
+- [x] WHITE์์ BLACK์ผ๋ก, BLACK์์ WHITE๋ก ํด์ ์ฐจ๋ก๋ก ๋ฐ๊พผ๋ค.
+- [์์ธ] ์์ ์ ํด์ด ์๋์๋ ์์ ์ ๋ง์ ์์ง์ด๋ ค๊ณ ํ๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.
+
+### Score
+
+- [x] ํ์ฌ๊น์ง ๋จ์ ์๋ ๋ง์ ๋ฐ๋ผ ์ ์๋ฅผ ๊ณ์ฐํ ์ ์์ด์ผ ํ๋ค.
+- [x] ๊ฐ ๋ง์ ์ ์๋ queen์ 9์ , rook์ 5์ , bishop์ 3์ , knight๋ 2.5์ ์ด๋ค.
+- [x] pawn์ ๊ธฐ๋ณธ ์ ์๋ 1์ ์ด๋ค.
+ - [x] ํ์ง๋ง ๊ฐ์ ์ธ๋ก์ค์ ๊ฐ์ ์์ ํฐ์ด ์๋ ๊ฒฝ์ฐ 1์ ์ด ์๋ 0.5์ ์ ์ค๋ค.
+
+### DB ์๋๋ฆฌ์ค
+- [x] ๊ฒ์ ์์์
+ - [x] ์งํ์ค์ด๋ ๊ฒ์์ด ์๋ค๋ฉด ํด๋น ๊ฒ์์ ๋ก๋ํด์ ์งํํ๋ค.
+ - [x] ์งํ์ค์ด๋ ๊ฒ์์ด ์๋ค๋ฉด ์๋ก์ด ๊ฒ์์ ์์ํ๋ค.
+- [x] ๊ฒ์ ์งํ์ค
+ - [x] status๋ฅผ ์
๋ ฅํ๊ฑฐ๋, ์๋๋ฐฉ์ ํน์ ์ก์ผ๋ฉด ๊ฒ์์ ์ข
๋ฃํ๋ค. ๊ทธ๋ฆฌ๊ณ DB๋ฅผ ๋ชจ๋ ์ง์ด๋ค.
+ - [x] ๊ทธ๋ ์ง ์๊ณ , end๋ฅผ ์
๋ ฅํ๋ค๋ฉด ๋ง์ง๋ง ๊ฒ์ ์ํ๋ฅผ DB์ ์ ์ฅํ๋ค.
+
+### DB DDL
+``` sql
+create table chess_game
+(
+ piece_id int auto_increment primary key,
+ piece_file varchar(20) not null,
+ piece_rank varchar(20) not null,
+ piece_type varchar(20) not null,
+ piece_team varchar(20) not null,
+ last_turn varchar(20) not null
+);
+``` | Unknown | DDL ๋ช
์ ์ข์์~
์ ๋ ๋ฆฌ๋ทฐ์ด ๋ถ๊ป ๋ฆฌ๋ทฐ๋ฐ์ ์ฌํญ ์ค ํ๋๋ฅผ ๋ง์๋๋ฆฌ๋ฉด ํ์ฌ chess_game ํ
์ด๋ธ์์ ๊ด๋ฆฌ๋๋ ๋ฐ์ดํฐ๋ค์ ๋ณด๋ฉด ํ
์ด๋ธ ๋ช
์ด chess_game์ด ์๋๋ผ piece๊ฐ ๋์ด์ผ ํ์ง ์์๊น ํ๋ ๊ฒ์
๋๋ค. |
@@ -43,7 +43,7 @@ set JAVA_EXE=java.exe
if "%ERRORLEVEL%" == "0" goto execute
echo.
-echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo ERROR: JAVA_HOME is not set and no 'java' gameCommand could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
@@ -65,7 +65,7 @@ echo location of your Java installation.
goto fail
:execute
-@rem Setup the command line
+@rem Setup the gameCommand line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
| Unknown | ์...? ์ด ํ์ผ์ command ๋ผ๋ ๋จ์ด๋ฅผ ์ ์ฒด ์นํํ๋ค๊ฐ ๊ฐ์ด ์์ ๋์ด ๋ฒ๋ฆฐ ๊ฒ ๊ฐ์ ๋ณด์ฌ์~ |
@@ -0,0 +1,12 @@
+package chess.database;
+
+public final class DbInfo {
+
+ public static String service_url = "jdbc:mysql://127.0.0.1:13306/chess?useSSL=false&serverTimezone=UTC";
+ public static String service_user = "root";
+ public static String service_password = "root";
+
+ public static String test_url = "jdbc:mysql://127.0.0.1:13306/chess_test?useSSL=false&serverTimezone=UTC";
+ public static String test_user = "root";
+ public static String test_password = "root";
+} | Java | ์ด ํด๋์ค์์ connection์ ๋ง๋ค์ด์ ๋์ ธ์ฃผ๋ ๊ฑด ์ด๋จ๊น์? |
@@ -0,0 +1,21 @@
+package chess;
+
+import chess.controller.ChessController;
+import chess.view.IOViewResolver;
+import chess.view.InputView;
+import chess.view.OutputView;
+
+import java.util.Scanner;
+
+public final class MainApp {
+
+ public static void main(String[] args) {
+ try (Scanner scanner = new Scanner(System.in)) {
+ final ChessController chessController = new ChessController(
+ new IOViewResolver(new InputView(scanner), new OutputView()));
+ chessController.process();
+ } catch (Exception exception) {
+ exception.printStackTrace();
+ }
+ }
+} | Java | ์์๊ด๋ฆฌ ์ฟ ์ธ ๐ |
@@ -0,0 +1,70 @@
+package chess.controller;
+
+import chess.domain.game.File;
+import chess.domain.game.Position;
+import chess.domain.game.Rank;
+
+import java.util.Arrays;
+import java.util.List;
+
+public enum GameCommand {
+ INIT,
+ START,
+ FIRST_MOVE,
+ MOVE,
+ STATUS,
+ END;
+
+ public static final String INVALID_COMMAND_MESSAGE = "์๋ชป๋ ์ปค๋งจ๋๋ฅผ ์
๋ ฅํ์์ต๋๋ค.";
+ public static final int SOURCE_INDEX = 1;
+ public static final int TARGET_INDEX = 2;
+ public static final int SOURCE_AND_TARGET_LENGTH = 2;
+ public static final int INPUT_SIZE = 3;
+ private static final int DEFAULT_COMMAND_INDEX = 0;
+
+ public static GameCommand from(final List<String> input) {
+ GameCommand result = Arrays.stream(values())
+ .filter(value -> value.name().equalsIgnoreCase(input.get(DEFAULT_COMMAND_INDEX)))
+ .findFirst()
+ .orElseThrow(() -> new IllegalArgumentException(INVALID_COMMAND_MESSAGE));
+ if (result == MOVE) {
+ validateMoveCommand(input);
+ }
+ return result;
+ }
+
+ private static void validateMoveCommand(List<String> input) {
+ if (input.size() != INPUT_SIZE) {
+ throw new IllegalArgumentException(INVALID_COMMAND_MESSAGE);
+ }
+ if (input.get(SOURCE_INDEX).length() != SOURCE_AND_TARGET_LENGTH ||
+ input.get(TARGET_INDEX).length() != SOURCE_AND_TARGET_LENGTH) {
+ throw new IllegalArgumentException(INVALID_COMMAND_MESSAGE);
+ }
+ }
+
+ public static Position getPosition(final List<String> input, final int index) {
+ final String targetPosition = input.get(index);
+ final int fileOrder = getFileOrder(targetPosition);
+ final int rankOrder = getRankOrder(targetPosition);
+ return Position.of(File.of(fileOrder), Rank.of(rankOrder));
+ }
+
+ private static int getFileOrder(final String command) {
+ final int charToIntDifference = 96;
+ return command.charAt(0) - charToIntDifference;
+ }
+
+ private static int getRankOrder(final String command) {
+ final char charToIntDifference = '0';
+ return command.charAt(1) - charToIntDifference;
+ }
+
+ public boolean isEnd() {
+ return this == END;
+ }
+
+ public boolean isFirstMove() {
+ return this == FIRST_MOVE;
+ }
+} | Java | ์ฒ์ GameCommand ํด๋์ค๋ฅผ ๋ณด๋๋ฐ Position์ ๊ตฌํ๋ ์ฝ๋๋ค์ด ์ ์ฌ๊ธฐ์ ๋ค์ด๊ฐ ์์๊น๊ฐ ์ข ๊ถ๊ธํ์์ต๋๋ค. ์๋ง ํํฌ๊ฐ input์ผ๋ก ๋ค์ด์จ command๋ฅผ ๊ฐ์ง๊ณ position์ ๊ตฌํ๋ ๊ธฐ๋ฅ์ด๋ผ๊ณ ์๊ฐํด์ GameCommand๋ก ๋ถ๋ฆฌํ์ ๊ฒ ๊ฐ์์.
์ ๋ผ๋ฉด ํด๋น ๊ธฐ๋ฅ๋ค์ file, rank, Position Enum์์ ์ฑ
์์ ์ง๋๋ก ํ์ ๊ฒ ๊ฐ์๋ฐ ํํฌ ์๊ฒฌ์ ์ด๋ ์ ์ง ๊ถ๊ธํด์~ |
@@ -0,0 +1,113 @@
+package chess.domain.game;
+
+import chess.domain.piece.Empty;
+import chess.domain.piece.Piece;
+import chess.domain.piece.PieceType;
+import chess.domain.piece.Team;
+import chess.domain.piece.pawn.BlackPawn;
+import chess.domain.piece.pawn.WhitePawn;
+import chess.dto.mapper.ParseToDto;
+import chess.dto.outputView.PrintBoardDto;
+import chess.dto.outputView.PrintTotalScoreDto;
+import chess.dto.outputView.PrintWinnerDto;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public final class ChessGame {
+
+ private static final int BOARD_LENGTH = 8;
+ public static final double TOTAL_BOARD_SIZE = Math.pow(BOARD_LENGTH, 2);
+
+ private final Map<Position, Piece> board;
+ private Turn turn;
+
+ private ChessGame(final Map<Position, Piece> board, final Turn turn) {
+ this.board = new HashMap<>(board);
+ this.turn = turn;
+ }
+
+ public static ChessGame of(final Map<Position, Piece> board) {
+ return of(board, Turn.create());
+ }
+
+ public static ChessGame of(final Map<Position, Piece> board, final Turn turn) {
+ if (board.size() != TOTAL_BOARD_SIZE) {
+ throw new IllegalArgumentException(
+ String.format("์ฒด์คํ์ ์ฌ์ด์ฆ๋ %d x %d ์ฌ์ผํฉ๋๋ค.", BOARD_LENGTH, BOARD_LENGTH));
+ }
+ return new ChessGame(board, turn);
+ }
+
+ public Piece move(final Position source, final Position target) {
+ final Piece sourcePiece = board.get(source);
+ final Piece targetPiece = board.get(target);
+ validateEmptyPiece(sourcePiece);
+ validateTurn(sourcePiece);
+ validatePath(sourcePiece.findPath(source, target, targetPiece.getTeam()));
+
+ switchPiece(source, target, sourcePiece);
+ turn = turn.next();
+ return targetPiece;
+ }
+
+ private void validateEmptyPiece(final Piece sourcePiece) {
+ if (sourcePiece.isEmpty()) {
+ throw new IllegalArgumentException("๊ธฐ๋ฌผ์ด ์๋ ๊ณณ์ ์ ํํ์
จ์ต๋๋ค.");
+ }
+ }
+
+ private void validateTurn(final Piece piece) {
+ if (!turn.isValidTurn(piece)) {
+ throw new IllegalStateException("ํด์ด ์ฌ๋ฐ๋ฅด์ง ์์ต๋๋ค. ํ์ฌ ํด : " + turn.getTeam());
+ }
+ }
+
+ private void validatePath(final List<Position> path) {
+ final boolean result = path.stream()
+ .allMatch(position -> board.get(position).isEmpty());
+ if (!result) {
+ throw new IllegalArgumentException("์ด๋ํ๋ ค๋ ๊ฒฝ๋ก์ ๊ธฐ๋ฌผ์ด ์กด์ฌํฉ๋๋ค.");
+ }
+ }
+
+ private void switchPiece(final Position source, final Position target, final Piece sourcePiece) {
+ board.put(target, checkInitialPawn(sourcePiece));
+ board.put(source, Empty.instance());
+ }
+
+ private Piece checkInitialPawn(final Piece piece) {
+ if (piece.isSamePieceTypeAs(PieceType.INITIAL_WHITE_PAWN)) {
+ return WhitePawn.instance();
+ }
+ if (piece.isSamePieceTypeAs(PieceType.INITIAL_BLACK_PAWN)) {
+ return BlackPawn.instance();
+ }
+ return piece;
+ }
+
+ public PrintWinnerDto getWinnerTeam(final Piece deadPiece) {
+ final Team deadPieceTeam = deadPiece.getTeam();
+ final Team opponentTeam = deadPieceTeam.getOpponentTeam();
+ return new PrintWinnerDto(opponentTeam.name());
+ }
+
+ public PrintTotalScoreDto calculateScore() {
+ return new PrintTotalScoreDto(
+ ScoreCalculator.calculateScoreByTeam(Team.WHITE, board),
+ ScoreCalculator.calculateScoreByTeam(Team.BLACK, board));
+ }
+
+ public PrintBoardDto printBoard() {
+ return ParseToDto.parseToPrintBoardDto(getBoard());
+ }
+
+ public Map<Position, Piece> getBoard() {
+ return Map.copyOf(board);
+ }
+
+ public Team getTurn() {
+ return turn.getTeam();
+ }
+} | Java | pawn์ ๋ํ ์ฒ๋ฆฌ ๋ก์ง์ ํฌํจํด์ ๊ธฐ๋ฌผ ์ด๋ ๋ก์ง์ด ์ ๋ง ๊น๋ํ๋ค์! ๐ฏ |
@@ -0,0 +1,31 @@
+//
+// SceneDelegate.swift
+// DrawingApp
+//
+// Created by ๊นํ๋ฆผ on 2023/03/28.
+//
+
+import UIKit
+
+class SceneDelegate: UIResponder, UIWindowSceneDelegate {
+
+ var window: UIWindow?
+
+
+ func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
+ guard let _ = (scene as? UIWindowScene) else { return }
+ }
+
+ func sceneDidDisconnect(_ scene: UIScene) { }
+
+ func sceneDidBecomeActive(_ scene: UIScene) { }
+
+ func sceneWillResignActive(_ scene: UIScene) { }
+
+ func sceneWillEnterForeground(_ scene: UIScene) { }
+
+ func sceneDidEnterBackground(_ scene: UIScene) { }
+
+
+}
+ | Swift | ํ์์๊ฑฐ๋ ์ฌ์ฉํ์ง ์๋ ๋ฉ์๋๋ ํ๋จํ์ฌ ์ญ์ ํ๋๊ฒ๋ ์ข์ ๊ฑฐ ๊ฐ์ต๋๋ค |
@@ -0,0 +1,91 @@
+//
+// ViewController.swift
+// DrawingApp
+//
+// Created by ๊นํ๋ฆผ on 2023/03/28.
+//
+
+import UIKit
+import OSLog
+
+class ViewController: UIViewController {
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ let rect1 = RectangleFactory.createRectangle()
+ os_log("\(rect1.description)")
+ }
+}
+
+protocol RectangleComponent {
+ var id:String { get }
+ var size:RectangleSize { get }
+ var position:RectanglePosition { get }
+ var backGroundColor:(red:Int, green:Int, blue:Int) { get }
+ var alpha:Int { get }
+}
+
+class RectangleSize {
+ private var width:Double = 150
+ private var height:Double = 120
+
+ func getWidth() -> Double {
+ return self.width
+ }
+ func getHeight() -> Double {
+ return self.height
+ }
+}
+class RectanglePosition {
+ private var X:Double
+ private var Y:Double
+
+ init(X: Double, Y: Double) {
+ self.X = X
+ self.Y = Y
+ }
+ func randomPosition() -> RectanglePosition {
+ let x = Double.random(in: 0...UIScreen.main.bounds.width)
+ let y = Double.random(in: 0...UIScreen.main.bounds.height)
+ return RectanglePosition(X: x, Y: y)
+ }
+ func getPositionX() -> Double {
+ return self.X
+ }
+ func getPositionY() -> Double {
+ return self.Y
+ }
+}
+
+
+class IdRandomizer {
+ func randomString() -> String {
+ let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+ var randomString = ""
+ for _ in 0..<9 {
+ let randomIndex = Int.random(in: 0..<letters.count)
+ let letter = letters[letters.index(letters.startIndex, offsetBy: randomIndex)]
+ randomString.append(letter)
+ }
+ return "\(randomString.prefix(3))-\(randomString.prefix(6).suffix(3))-\(randomString.suffix(3))"
+ }
+}
+
+class RectangleFactory {
+ static func createRectangle() -> Rectangle {
+ let id = IdRandomizer().randomString()
+ let size = RectangleSize()
+ let position = RectanglePosition(X: 0, Y: 0).randomPosition()
+ let backGroundColor = (red: Int.random(in: 0...255), green: Int.random(in: 0...255), blue: Int.random(in: 0...255))
+ let alpha = Int.random(in: 1...10)
+
+ return Rectangle(
+ id: id,
+ size: size,
+ position: position,
+ backGroundColor: backGroundColor,
+ alpha: alpha
+ )
+ }
+} | Swift | ์ขํ ์์ ํ ๊ฐ๋ฅ์ฑ์ด ์๋ค๋ฉด ์์๋ก ์ ์ธํ๋ ๊ฒ๋ ์ข์๋ณด์
๋๋ค |
@@ -0,0 +1,91 @@
+//
+// ViewController.swift
+// DrawingApp
+//
+// Created by ๊นํ๋ฆผ on 2023/03/28.
+//
+
+import UIKit
+import OSLog
+
+class ViewController: UIViewController {
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ let rect1 = RectangleFactory.createRectangle()
+ os_log("\(rect1.description)")
+ }
+}
+
+protocol RectangleComponent {
+ var id:String { get }
+ var size:RectangleSize { get }
+ var position:RectanglePosition { get }
+ var backGroundColor:(red:Int, green:Int, blue:Int) { get }
+ var alpha:Int { get }
+}
+
+class RectangleSize {
+ private var width:Double = 150
+ private var height:Double = 120
+
+ func getWidth() -> Double {
+ return self.width
+ }
+ func getHeight() -> Double {
+ return self.height
+ }
+}
+class RectanglePosition {
+ private var X:Double
+ private var Y:Double
+
+ init(X: Double, Y: Double) {
+ self.X = X
+ self.Y = Y
+ }
+ func randomPosition() -> RectanglePosition {
+ let x = Double.random(in: 0...UIScreen.main.bounds.width)
+ let y = Double.random(in: 0...UIScreen.main.bounds.height)
+ return RectanglePosition(X: x, Y: y)
+ }
+ func getPositionX() -> Double {
+ return self.X
+ }
+ func getPositionY() -> Double {
+ return self.Y
+ }
+}
+
+
+class IdRandomizer {
+ func randomString() -> String {
+ let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+ var randomString = ""
+ for _ in 0..<9 {
+ let randomIndex = Int.random(in: 0..<letters.count)
+ let letter = letters[letters.index(letters.startIndex, offsetBy: randomIndex)]
+ randomString.append(letter)
+ }
+ return "\(randomString.prefix(3))-\(randomString.prefix(6).suffix(3))-\(randomString.suffix(3))"
+ }
+}
+
+class RectangleFactory {
+ static func createRectangle() -> Rectangle {
+ let id = IdRandomizer().randomString()
+ let size = RectangleSize()
+ let position = RectanglePosition(X: 0, Y: 0).randomPosition()
+ let backGroundColor = (red: Int.random(in: 0...255), green: Int.random(in: 0...255), blue: Int.random(in: 0...255))
+ let alpha = Int.random(in: 1...10)
+
+ return Rectangle(
+ id: id,
+ size: size,
+ position: position,
+ backGroundColor: backGroundColor,
+ alpha: alpha
+ )
+ }
+} | Swift | ๊ฐ์ธ์ ์ผ๋ก ํ์ ๊ฐ์ฒด๋ ํ๋กํ ์ฝ๋ค์ ๋ค๋ฅธ ํ์ผ๋ก ๋ถ๋ฆฌํ๋ ๊ฒ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค
์ ๋ ๋ถ๋ฆฌํ์ ๋ ์ถํ์ ์ฝ๋ ์์ ์ ์ฐพ์๊ฐ๊ธฐ ์ฌ์์ ์ข์์ต๋๋ค |
@@ -0,0 +1,91 @@
+//
+// ViewController.swift
+// DrawingApp
+//
+// Created by ๊นํ๋ฆผ on 2023/03/28.
+//
+
+import UIKit
+import OSLog
+
+class ViewController: UIViewController {
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ let rect1 = RectangleFactory.createRectangle()
+ os_log("\(rect1.description)")
+ }
+}
+
+protocol RectangleComponent {
+ var id:String { get }
+ var size:RectangleSize { get }
+ var position:RectanglePosition { get }
+ var backGroundColor:(red:Int, green:Int, blue:Int) { get }
+ var alpha:Int { get }
+}
+
+class RectangleSize {
+ private var width:Double = 150
+ private var height:Double = 120
+
+ func getWidth() -> Double {
+ return self.width
+ }
+ func getHeight() -> Double {
+ return self.height
+ }
+}
+class RectanglePosition {
+ private var X:Double
+ private var Y:Double
+
+ init(X: Double, Y: Double) {
+ self.X = X
+ self.Y = Y
+ }
+ func randomPosition() -> RectanglePosition {
+ let x = Double.random(in: 0...UIScreen.main.bounds.width)
+ let y = Double.random(in: 0...UIScreen.main.bounds.height)
+ return RectanglePosition(X: x, Y: y)
+ }
+ func getPositionX() -> Double {
+ return self.X
+ }
+ func getPositionY() -> Double {
+ return self.Y
+ }
+}
+
+
+class IdRandomizer {
+ func randomString() -> String {
+ let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+ var randomString = ""
+ for _ in 0..<9 {
+ let randomIndex = Int.random(in: 0..<letters.count)
+ let letter = letters[letters.index(letters.startIndex, offsetBy: randomIndex)]
+ randomString.append(letter)
+ }
+ return "\(randomString.prefix(3))-\(randomString.prefix(6).suffix(3))-\(randomString.suffix(3))"
+ }
+}
+
+class RectangleFactory {
+ static func createRectangle() -> Rectangle {
+ let id = IdRandomizer().randomString()
+ let size = RectangleSize()
+ let position = RectanglePosition(X: 0, Y: 0).randomPosition()
+ let backGroundColor = (red: Int.random(in: 0...255), green: Int.random(in: 0...255), blue: Int.random(in: 0...255))
+ let alpha = Int.random(in: 1...10)
+
+ return Rectangle(
+ id: id,
+ size: size,
+ position: position,
+ backGroundColor: backGroundColor,
+ alpha: alpha
+ )
+ }
+} | Swift | ํ๋ผ๋ฏธํฐ๋ฅผ ์ค๋ก ๋๋ ์ฃผ์ ๋ฐฉ์ ์ฝ๊ธฐ ํธํ๊ณ ๊น ๊ด๋ฆฌํ๊ธฐ ์์ํ๋ค์
์ ๋ ์นดํผ์นดํผ ํด๋๋ ๊น์? |
@@ -0,0 +1,32 @@
+//
+// Rectangle.swift
+// DrawingApp
+//
+// Created by ๊นํ๋ฆผ on 2023/03/30.
+//
+
+import Foundation
+
+class Rectangle : RectangleComponent {
+ let id:String
+ let size:RectangleSize
+ let position:RectanglePosition
+ let backGroundColor:(red:Int, green:Int, blue:Int)
+ let alpha:Int
+
+ init(id:String, size:RectangleSize, position:RectanglePosition, backGroundColor:(red:Int, green:Int, blue:Int), alpha:Int) {
+
+ self.id = id
+ self.size = size
+ self.position = position
+ self.backGroundColor = backGroundColor
+ self.alpha = alpha
+ }
+
+}
+
+extension Rectangle : CustomStringConvertible {
+ var description: String {
+ return "(\(id), X:\(position.getPositionX()), Y\(position.getPositionY()):, W\(size.getWidth()), H\(size.getHeight()), R:\(backGroundColor.red), G:\(backGroundColor.green), B:\(backGroundColor.blue), Alpha:\(alpha))"
+ }
+} | Swift | Color ํํํ์์ผ๋ก ํ๋ฒ์ ์ฌ๋ฌ๊ฐ์ ํ๋ผ๋ฏธํฐ๋ฅผ ๋ฐ์ ์ ์๋์ง ๋ชฐ๋๋ค์
ํ ์ ๋ฐฐ์๊ฐ์ |
@@ -0,0 +1,91 @@
+//
+// ViewController.swift
+// DrawingApp
+//
+// Created by ๊นํ๋ฆผ on 2023/03/28.
+//
+
+import UIKit
+import OSLog
+
+class ViewController: UIViewController {
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ let rect1 = RectangleFactory.createRectangle()
+ os_log("\(rect1.description)")
+ }
+}
+
+protocol RectangleComponent {
+ var id:String { get }
+ var size:RectangleSize { get }
+ var position:RectanglePosition { get }
+ var backGroundColor:(red:Int, green:Int, blue:Int) { get }
+ var alpha:Int { get }
+}
+
+class RectangleSize {
+ private var width:Double = 150
+ private var height:Double = 120
+
+ func getWidth() -> Double {
+ return self.width
+ }
+ func getHeight() -> Double {
+ return self.height
+ }
+}
+class RectanglePosition {
+ private var X:Double
+ private var Y:Double
+
+ init(X: Double, Y: Double) {
+ self.X = X
+ self.Y = Y
+ }
+ func randomPosition() -> RectanglePosition {
+ let x = Double.random(in: 0...UIScreen.main.bounds.width)
+ let y = Double.random(in: 0...UIScreen.main.bounds.height)
+ return RectanglePosition(X: x, Y: y)
+ }
+ func getPositionX() -> Double {
+ return self.X
+ }
+ func getPositionY() -> Double {
+ return self.Y
+ }
+}
+
+
+class IdRandomizer {
+ func randomString() -> String {
+ let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+ var randomString = ""
+ for _ in 0..<9 {
+ let randomIndex = Int.random(in: 0..<letters.count)
+ let letter = letters[letters.index(letters.startIndex, offsetBy: randomIndex)]
+ randomString.append(letter)
+ }
+ return "\(randomString.prefix(3))-\(randomString.prefix(6).suffix(3))-\(randomString.suffix(3))"
+ }
+}
+
+class RectangleFactory {
+ static func createRectangle() -> Rectangle {
+ let id = IdRandomizer().randomString()
+ let size = RectangleSize()
+ let position = RectanglePosition(X: 0, Y: 0).randomPosition()
+ let backGroundColor = (red: Int.random(in: 0...255), green: Int.random(in: 0...255), blue: Int.random(in: 0...255))
+ let alpha = Int.random(in: 1...10)
+
+ return Rectangle(
+ id: id,
+ size: size,
+ position: position,
+ backGroundColor: backGroundColor,
+ alpha: alpha
+ )
+ }
+} | Swift | ๋ชจ๋ธ ํ์ ํ์
์ ํด๋์ค๋ก ํ์
จ๋๋ฐ ์ ํํ์ ๊ธฐ์ค์ด ์๋์ง ๊ถ๊ธํด์ |
@@ -0,0 +1,91 @@
+//
+// ViewController.swift
+// DrawingApp
+//
+// Created by ๊นํ๋ฆผ on 2023/03/28.
+//
+
+import UIKit
+import OSLog
+
+class ViewController: UIViewController {
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ let rect1 = RectangleFactory.createRectangle()
+ os_log("\(rect1.description)")
+ }
+}
+
+protocol RectangleComponent {
+ var id:String { get }
+ var size:RectangleSize { get }
+ var position:RectanglePosition { get }
+ var backGroundColor:(red:Int, green:Int, blue:Int) { get }
+ var alpha:Int { get }
+}
+
+class RectangleSize {
+ private var width:Double = 150
+ private var height:Double = 120
+
+ func getWidth() -> Double {
+ return self.width
+ }
+ func getHeight() -> Double {
+ return self.height
+ }
+}
+class RectanglePosition {
+ private var X:Double
+ private var Y:Double
+
+ init(X: Double, Y: Double) {
+ self.X = X
+ self.Y = Y
+ }
+ func randomPosition() -> RectanglePosition {
+ let x = Double.random(in: 0...UIScreen.main.bounds.width)
+ let y = Double.random(in: 0...UIScreen.main.bounds.height)
+ return RectanglePosition(X: x, Y: y)
+ }
+ func getPositionX() -> Double {
+ return self.X
+ }
+ func getPositionY() -> Double {
+ return self.Y
+ }
+}
+
+
+class IdRandomizer {
+ func randomString() -> String {
+ let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+ var randomString = ""
+ for _ in 0..<9 {
+ let randomIndex = Int.random(in: 0..<letters.count)
+ let letter = letters[letters.index(letters.startIndex, offsetBy: randomIndex)]
+ randomString.append(letter)
+ }
+ return "\(randomString.prefix(3))-\(randomString.prefix(6).suffix(3))-\(randomString.suffix(3))"
+ }
+}
+
+class RectangleFactory {
+ static func createRectangle() -> Rectangle {
+ let id = IdRandomizer().randomString()
+ let size = RectangleSize()
+ let position = RectanglePosition(X: 0, Y: 0).randomPosition()
+ let backGroundColor = (red: Int.random(in: 0...255), green: Int.random(in: 0...255), blue: Int.random(in: 0...255))
+ let alpha = Int.random(in: 1...10)
+
+ return Rectangle(
+ id: id,
+ size: size,
+ position: position,
+ backGroundColor: backGroundColor,
+ alpha: alpha
+ )
+ }
+} | Swift | ๋ง์ฝ ์ธ๋ถ์์ ๋ฐ๋์ ์ ๊ทผํด์ผ๋ง ํ๋ค๋ฉด private์ ๋นผ๋๊ฒ๋ ์ข์๋ณด์
๋๋ค |
@@ -0,0 +1,91 @@
+//
+// ViewController.swift
+// DrawingApp
+//
+// Created by ๊นํ๋ฆผ on 2023/03/28.
+//
+
+import UIKit
+import OSLog
+
+class ViewController: UIViewController {
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ let rect1 = RectangleFactory.createRectangle()
+ os_log("\(rect1.description)")
+ }
+}
+
+protocol RectangleComponent {
+ var id:String { get }
+ var size:RectangleSize { get }
+ var position:RectanglePosition { get }
+ var backGroundColor:(red:Int, green:Int, blue:Int) { get }
+ var alpha:Int { get }
+}
+
+class RectangleSize {
+ private var width:Double = 150
+ private var height:Double = 120
+
+ func getWidth() -> Double {
+ return self.width
+ }
+ func getHeight() -> Double {
+ return self.height
+ }
+}
+class RectanglePosition {
+ private var X:Double
+ private var Y:Double
+
+ init(X: Double, Y: Double) {
+ self.X = X
+ self.Y = Y
+ }
+ func randomPosition() -> RectanglePosition {
+ let x = Double.random(in: 0...UIScreen.main.bounds.width)
+ let y = Double.random(in: 0...UIScreen.main.bounds.height)
+ return RectanglePosition(X: x, Y: y)
+ }
+ func getPositionX() -> Double {
+ return self.X
+ }
+ func getPositionY() -> Double {
+ return self.Y
+ }
+}
+
+
+class IdRandomizer {
+ func randomString() -> String {
+ let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+ var randomString = ""
+ for _ in 0..<9 {
+ let randomIndex = Int.random(in: 0..<letters.count)
+ let letter = letters[letters.index(letters.startIndex, offsetBy: randomIndex)]
+ randomString.append(letter)
+ }
+ return "\(randomString.prefix(3))-\(randomString.prefix(6).suffix(3))-\(randomString.suffix(3))"
+ }
+}
+
+class RectangleFactory {
+ static func createRectangle() -> Rectangle {
+ let id = IdRandomizer().randomString()
+ let size = RectangleSize()
+ let position = RectanglePosition(X: 0, Y: 0).randomPosition()
+ let backGroundColor = (red: Int.random(in: 0...255), green: Int.random(in: 0...255), blue: Int.random(in: 0...255))
+ let alpha = Int.random(in: 1...10)
+
+ return Rectangle(
+ id: id,
+ size: size,
+ position: position,
+ backGroundColor: backGroundColor,
+ alpha: alpha
+ )
+ }
+} | Swift | class func ๋์ static func์ ์ฐ์ ์ด์ ๋ ์ค๋ฒ๋ผ์ด๋ฉ์ด ๋ถ๊ฐ๋ฅํ๋๋ก ์๋ํ์ ๊ฑฐ ๋ง์๊น์?๐๐ป |
@@ -0,0 +1,91 @@
+//
+// ViewController.swift
+// DrawingApp
+//
+// Created by ๊นํ๋ฆผ on 2023/03/28.
+//
+
+import UIKit
+import OSLog
+
+class ViewController: UIViewController {
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ let rect1 = RectangleFactory.createRectangle()
+ os_log("\(rect1.description)")
+ }
+}
+
+protocol RectangleComponent {
+ var id:String { get }
+ var size:RectangleSize { get }
+ var position:RectanglePosition { get }
+ var backGroundColor:(red:Int, green:Int, blue:Int) { get }
+ var alpha:Int { get }
+}
+
+class RectangleSize {
+ private var width:Double = 150
+ private var height:Double = 120
+
+ func getWidth() -> Double {
+ return self.width
+ }
+ func getHeight() -> Double {
+ return self.height
+ }
+}
+class RectanglePosition {
+ private var X:Double
+ private var Y:Double
+
+ init(X: Double, Y: Double) {
+ self.X = X
+ self.Y = Y
+ }
+ func randomPosition() -> RectanglePosition {
+ let x = Double.random(in: 0...UIScreen.main.bounds.width)
+ let y = Double.random(in: 0...UIScreen.main.bounds.height)
+ return RectanglePosition(X: x, Y: y)
+ }
+ func getPositionX() -> Double {
+ return self.X
+ }
+ func getPositionY() -> Double {
+ return self.Y
+ }
+}
+
+
+class IdRandomizer {
+ func randomString() -> String {
+ let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+ var randomString = ""
+ for _ in 0..<9 {
+ let randomIndex = Int.random(in: 0..<letters.count)
+ let letter = letters[letters.index(letters.startIndex, offsetBy: randomIndex)]
+ randomString.append(letter)
+ }
+ return "\(randomString.prefix(3))-\(randomString.prefix(6).suffix(3))-\(randomString.suffix(3))"
+ }
+}
+
+class RectangleFactory {
+ static func createRectangle() -> Rectangle {
+ let id = IdRandomizer().randomString()
+ let size = RectangleSize()
+ let position = RectanglePosition(X: 0, Y: 0).randomPosition()
+ let backGroundColor = (red: Int.random(in: 0...255), green: Int.random(in: 0...255), blue: Int.random(in: 0...255))
+ let alpha = Int.random(in: 1...10)
+
+ return Rectangle(
+ id: id,
+ size: size,
+ position: position,
+ backGroundColor: backGroundColor,
+ alpha: alpha
+ )
+ }
+} | Swift | [UIScreen.main ๊ณต์๋ฌธ์](https://developer.apple.com/documentation/uikit/uiscreen/1617815-main)
์ฐ์ฐํ Apple Documentation์์ ๋ฐ๊ฒฌํ๋๋ฐ, main์ Deprecated ๋์๋๋ผ๊ณ ์
์๋จ ๊ณต์๋ฌธ์ ๋ด์ฉ์์ ์ถ์ฒํ๋ ๋ค๋ฅธ๋ฐฉ๋ฒ์ ์ฌ์ฉํด๋ณด์๋ ๊ฒ๋ ์ข์๊ฑฐ๊ฐ์์ |
@@ -0,0 +1,91 @@
+//
+// ViewController.swift
+// DrawingApp
+//
+// Created by ๊นํ๋ฆผ on 2023/03/28.
+//
+
+import UIKit
+import OSLog
+
+class ViewController: UIViewController {
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ let rect1 = RectangleFactory.createRectangle()
+ os_log("\(rect1.description)")
+ }
+}
+
+protocol RectangleComponent {
+ var id:String { get }
+ var size:RectangleSize { get }
+ var position:RectanglePosition { get }
+ var backGroundColor:(red:Int, green:Int, blue:Int) { get }
+ var alpha:Int { get }
+}
+
+class RectangleSize {
+ private var width:Double = 150
+ private var height:Double = 120
+
+ func getWidth() -> Double {
+ return self.width
+ }
+ func getHeight() -> Double {
+ return self.height
+ }
+}
+class RectanglePosition {
+ private var X:Double
+ private var Y:Double
+
+ init(X: Double, Y: Double) {
+ self.X = X
+ self.Y = Y
+ }
+ func randomPosition() -> RectanglePosition {
+ let x = Double.random(in: 0...UIScreen.main.bounds.width)
+ let y = Double.random(in: 0...UIScreen.main.bounds.height)
+ return RectanglePosition(X: x, Y: y)
+ }
+ func getPositionX() -> Double {
+ return self.X
+ }
+ func getPositionY() -> Double {
+ return self.Y
+ }
+}
+
+
+class IdRandomizer {
+ func randomString() -> String {
+ let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+ var randomString = ""
+ for _ in 0..<9 {
+ let randomIndex = Int.random(in: 0..<letters.count)
+ let letter = letters[letters.index(letters.startIndex, offsetBy: randomIndex)]
+ randomString.append(letter)
+ }
+ return "\(randomString.prefix(3))-\(randomString.prefix(6).suffix(3))-\(randomString.suffix(3))"
+ }
+}
+
+class RectangleFactory {
+ static func createRectangle() -> Rectangle {
+ let id = IdRandomizer().randomString()
+ let size = RectangleSize()
+ let position = RectanglePosition(X: 0, Y: 0).randomPosition()
+ let backGroundColor = (red: Int.random(in: 0...255), green: Int.random(in: 0...255), blue: Int.random(in: 0...255))
+ let alpha = Int.random(in: 1...10)
+
+ return Rectangle(
+ id: id,
+ size: size,
+ position: position,
+ backGroundColor: backGroundColor,
+ alpha: alpha
+ )
+ }
+} | Swift | ํ์ต ๊ฐ์ด๋์์ ์ฐธ๊ณ ํ๋๋ฐ,
๋ฉ์๋ ๋ค์ด๋ฐ์ ํจ์๋ก ์์ฑํ๋๊ฒ ์ข๋ค๊ณ ๋์ด์์ด ์ฐธ๊ณ ํ์๋ฉด ์ข์ ๋ณด์
๋๋ค |
@@ -0,0 +1,91 @@
+//
+// ViewController.swift
+// DrawingApp
+//
+// Created by ๊นํ๋ฆผ on 2023/03/28.
+//
+
+import UIKit
+import OSLog
+
+class ViewController: UIViewController {
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ let rect1 = RectangleFactory.createRectangle()
+ os_log("\(rect1.description)")
+ }
+}
+
+protocol RectangleComponent {
+ var id:String { get }
+ var size:RectangleSize { get }
+ var position:RectanglePosition { get }
+ var backGroundColor:(red:Int, green:Int, blue:Int) { get }
+ var alpha:Int { get }
+}
+
+class RectangleSize {
+ private var width:Double = 150
+ private var height:Double = 120
+
+ func getWidth() -> Double {
+ return self.width
+ }
+ func getHeight() -> Double {
+ return self.height
+ }
+}
+class RectanglePosition {
+ private var X:Double
+ private var Y:Double
+
+ init(X: Double, Y: Double) {
+ self.X = X
+ self.Y = Y
+ }
+ func randomPosition() -> RectanglePosition {
+ let x = Double.random(in: 0...UIScreen.main.bounds.width)
+ let y = Double.random(in: 0...UIScreen.main.bounds.height)
+ return RectanglePosition(X: x, Y: y)
+ }
+ func getPositionX() -> Double {
+ return self.X
+ }
+ func getPositionY() -> Double {
+ return self.Y
+ }
+}
+
+
+class IdRandomizer {
+ func randomString() -> String {
+ let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+ var randomString = ""
+ for _ in 0..<9 {
+ let randomIndex = Int.random(in: 0..<letters.count)
+ let letter = letters[letters.index(letters.startIndex, offsetBy: randomIndex)]
+ randomString.append(letter)
+ }
+ return "\(randomString.prefix(3))-\(randomString.prefix(6).suffix(3))-\(randomString.suffix(3))"
+ }
+}
+
+class RectangleFactory {
+ static func createRectangle() -> Rectangle {
+ let id = IdRandomizer().randomString()
+ let size = RectangleSize()
+ let position = RectanglePosition(X: 0, Y: 0).randomPosition()
+ let backGroundColor = (red: Int.random(in: 0...255), green: Int.random(in: 0...255), blue: Int.random(in: 0...255))
+ let alpha = Int.random(in: 1...10)
+
+ return Rectangle(
+ id: id,
+ size: size,
+ position: position,
+ backGroundColor: backGroundColor,
+ alpha: alpha
+ )
+ }
+} | Swift | uuid ์์ด ๋ง๋๋ ๋ฐฉ์์ด ์๋์ง๋ ๋ชฐ๋๋๋ฐ, ์ ์ ํ๊ณ ๋ ๊น๋ํ ๋ฐฉ์์ด๋ค์๐๐ป |
@@ -0,0 +1,91 @@
+//
+// ViewController.swift
+// DrawingApp
+//
+// Created by ๊นํ๋ฆผ on 2023/03/28.
+//
+
+import UIKit
+import OSLog
+
+class ViewController: UIViewController {
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ let rect1 = RectangleFactory.createRectangle()
+ os_log("\(rect1.description)")
+ }
+}
+
+protocol RectangleComponent {
+ var id:String { get }
+ var size:RectangleSize { get }
+ var position:RectanglePosition { get }
+ var backGroundColor:(red:Int, green:Int, blue:Int) { get }
+ var alpha:Int { get }
+}
+
+class RectangleSize {
+ private var width:Double = 150
+ private var height:Double = 120
+
+ func getWidth() -> Double {
+ return self.width
+ }
+ func getHeight() -> Double {
+ return self.height
+ }
+}
+class RectanglePosition {
+ private var X:Double
+ private var Y:Double
+
+ init(X: Double, Y: Double) {
+ self.X = X
+ self.Y = Y
+ }
+ func randomPosition() -> RectanglePosition {
+ let x = Double.random(in: 0...UIScreen.main.bounds.width)
+ let y = Double.random(in: 0...UIScreen.main.bounds.height)
+ return RectanglePosition(X: x, Y: y)
+ }
+ func getPositionX() -> Double {
+ return self.X
+ }
+ func getPositionY() -> Double {
+ return self.Y
+ }
+}
+
+
+class IdRandomizer {
+ func randomString() -> String {
+ let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+ var randomString = ""
+ for _ in 0..<9 {
+ let randomIndex = Int.random(in: 0..<letters.count)
+ let letter = letters[letters.index(letters.startIndex, offsetBy: randomIndex)]
+ randomString.append(letter)
+ }
+ return "\(randomString.prefix(3))-\(randomString.prefix(6).suffix(3))-\(randomString.suffix(3))"
+ }
+}
+
+class RectangleFactory {
+ static func createRectangle() -> Rectangle {
+ let id = IdRandomizer().randomString()
+ let size = RectangleSize()
+ let position = RectanglePosition(X: 0, Y: 0).randomPosition()
+ let backGroundColor = (red: Int.random(in: 0...255), green: Int.random(in: 0...255), blue: Int.random(in: 0...255))
+ let alpha = Int.random(in: 1...10)
+
+ return Rectangle(
+ id: id,
+ size: size,
+ position: position,
+ backGroundColor: backGroundColor,
+ alpha: alpha
+ )
+ }
+} | Swift | ํ๋กํ ์ฝ์ ์ ์ธ๋ ํ๋กํผํฐ๋ค์ ์ฑํํ์ ๋ private ์ ๊ทผ์ ์ด์๋ฅผ ์ฌ์ฉํ์ง ๋ชปํ๋ ๊ฑธ๋ก ์๊ณ ์์ต๋๋ค.
์ ๊ทผ์ ์ด์๊ฐ ํ์ํ ์์๋ค๋ง ํ๋กํ ์ฝ์ ์ถ๊ฐํ๋ ๊ฒ๋ ์ข์ ๋ณด์
๋๋ค. |
@@ -1,8 +1,8 @@
'use client';
import { ReactNode } from 'react';
-import { useInView } from 'react-intersection-observer';
+import { keyframes } from '@emotion/react';
import { Box, Card, CardMedia, SxProps, Typography } from '@mui/material';
import { Theme } from '@mui/system';
@@ -14,40 +14,49 @@ interface CommentCardProps {
isFilled?: boolean;
isCharacter?: boolean;
isChat?: boolean;
+ isFixed?: boolean;
sx?: SxProps<Theme>;
+ positionY?: string;
}
+const gradientAnimation = keyframes`
+ 0% {
+ background-position: 0% 50%;
+ }
+ 50% {
+ background-position: 100% 50%;
+ }
+ 100% {
+ background-position: 0% 50%;
+ }
+`;
+
const CommentCard = ({
content,
isStroke = false,
isFilled = false,
isCharacter = false,
isChat = false,
+ isFixed = false,
sx,
+ positionY = '40px',
}: CommentCardProps) => {
- const { ref, inView } = useInView({
- threshold: 0.1,
- });
-
return (
<Card
- ref={ref}
sx={{
display: 'flex',
boxShadow: 'none',
alignItems: 'center',
bgcolor: 'transparent',
- ...(isChat && {
- opacity: inView ? 1 : 0,
- transform: inView ? 'translateY(0)' : 'translateY(20px)',
- transition: 'opacity 0.6s ease-out, transform 0.6s ease-out',
- }),
- ...(!isChat && {
- width: '100%',
- }),
- ...(!isCharacter && {
- mb: 1.3,
- }),
+ position: isFixed ? 'fixed' : 'relative',
+ bottom: isFixed ? positionY : 'unset',
+ right: isFixed ? '20px' : 'unset',
+ zIndex: isFixed ? 9999 : 'unset',
+ transition: 'transform 0.3s ease-in-out',
+ '&:hover': {
+ transform: 'scale(1.1)',
+ },
+ ...sx,
}}
>
{isCharacter && (
@@ -59,19 +68,21 @@ const CommentCard = ({
borderRadius: 5,
ml: 1,
padding: '2px',
- background: isStroke ? `linear-gradient(${color.gradient_blue_dark}, ${color.gradient_blue_light})` : 'none',
- ...(!isChat && {
- width: '100%',
- }),
+ background: isStroke
+ ? `linear-gradient(45deg, ${color.gradient_blue_dark}, ${color.gradient_blue_light})`
+ : 'none',
+ width: '100%',
}}
>
<Box
borderRadius="18px"
padding={2}
sx={{
background: isFilled
- ? `linear-gradient(${color.gradient_blue_dark}, ${color.gradient_blue_light})`
+ ? `linear-gradient(45deg, ${color.gradient_blue_dark}, ${color.gradient_blue_light})`
: 'white',
+ backgroundSize: '200% 200%',
+ animation: isFixed && isFilled ? `${gradientAnimation} 6s ease infinite` : 'none',
...sx,
}}
> | Unknown | ์ธ์ฌ์ดํธ์ ์ฑ๋ด์ ํฌํจํ ๋ชจ๋ ๋งํ์ ์นด๋์ ๋ง์ฐ์ค๋ฅผ ํธ๋ฒํ๋ฉด ์ปค์ง๋ ํจ๊ณผ๊ฐ ๋ํ๋์ ์กฐ๊ฑด์ ์ฃผ์
์ผ ํ ๊ฒ ๊ฐ์์~!
์ง๊ธ ๋น์ฅ ์ฐ์ด๋ ๊ณณ์ด ์ด๊ฒ๋ฐ์ ์์ผ๋ `isFixed`๋ก ํ๊ฑฐ๋ ๋ค๋ฅธ ์์ฑ ํ๋ ์ถ๊ฐํด์ฃผ์
๋ ๋๊ณ ๋ง์๋๋ก ํ์์ง์ฉ~! |
@@ -0,0 +1,83 @@
+package christmas.service;
+
+import christmas.constant.Constant;
+import christmas.domain.Badge;
+import christmas.domain.Benefit;
+import christmas.domain.Event;
+import christmas.domain.OrderMenu;
+import christmas.view.input.template.InputCallback;
+import christmas.view.input.template.InputTemplate;
+
+public class ChristmasService {
+
+ private final InputTemplate inputTemplate;
+
+ public ChristmasService() {
+ this.inputTemplate = new InputTemplate();
+ }
+
+ public <T> T getInputRequestResult(InputCallback<T> callback) {
+ return inputTemplate.execute(callback);
+ }
+
+ public Benefit getBenefit(OrderMenu orderMenu, int day) {
+ Benefit benefit = new Benefit();
+ addDiscountIntoBenefitDetails(orderMenu, benefit, day);
+ return benefit;
+ }
+
+ public String getOrderMenuDetails(OrderMenu orderMenu) {
+ return orderMenu.detailsToString();
+ }
+
+ public String getTotalPriceBeforeDiscount(OrderMenu orderMenu) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), orderMenu.calculateTotalPrice());
+ }
+
+ public String getPresentationMenu(Benefit benefit) {
+ return benefit.presentationMenuToString();
+ }
+
+ public String getBenefitDetails(Benefit benefit) {
+ return benefit.detailsToString();
+ }
+
+ public String getTotalDiscount(Benefit benefit) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), benefit.calculateTotalDiscount());
+ }
+
+ public String getTotalPriceAfterDiscount(OrderMenu orderMenu, Benefit benefit) {
+ int totalPrice = orderMenu.calculateTotalPrice();
+ int totalDiscount = benefit.calculateTotalDiscount();
+ totalPrice += (totalDiscount - benefit.calculatePresentationPrice());
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), totalPrice);
+ }
+
+ public String getBadge(Benefit benefit) {
+ return Badge.findByTotalDiscount(benefit.calculateTotalDiscount());
+ }
+
+
+ private void addDiscountIntoBenefitDetails(OrderMenu orderMenu, Benefit benefit, int day) {
+ Event.findAllByDay(day)
+ .stream()
+ .filter(event -> orderMenu.calculateTotalPrice() > event.getCondition())
+ .forEach(event -> benefit.addDiscountIntoDetails(event, calculateDiscount(orderMenu, event, day)));
+ }
+
+ private int calculateDiscount(OrderMenu orderMenu, Event event, int day) {
+ int result = 0;
+ int orderMenuCount = orderMenu.countMenuByEventTarget(event.getTarget());
+ int discount = event.getDiscount();
+ int discountFromTotal = event.getDiscountFromTotal();
+ result -= (discount * orderMenuCount) + discountFromTotal;
+
+ if (event == Event.CHRISTMAS && day <= 25) {
+ result -= discount * (day - 1) + 1000;
+ }
+ if (event == Event.PRESENTATION) {
+ result -= discount;
+ }
+ return result;
+ }
+} | Java | ์์์ inputView์ ๋ฉ์๋๋ฅผ ๋๊ฒจ๋ฐ๊ณ ์คํํ๋ ๋ชจ์ต์ด๋๋ฐ, ๊ทธ๋ฅ ChristmasController์์ ์งํํ๋ ๊ฒ ์ข์์ ๊ฒ ๊ฐ์์. ๊ตณ์ด ์๋น์ค๊น์ง ๊ฑธ์น ํ์๊ฐ ์์์ ๊ฒ ๊ฐ์์.
์๋น์ค ๊ฐ์ฒด ๋ด์์ ํด๋น ๋ฉ์๋๊ฐ ์ฐ์ธ ๊ฒ๋ ์๋๊ณ , ์ค๋ก์ง ์ปจํธ๋กค๋ฌ์์๋ง ์ด ๋ฉ์๋๊ฐ ํธ์ถ๋๊ณ ์์ด์. |
@@ -0,0 +1,72 @@
+package christmas.domain;
+
+import christmas.constant.Constant;
+import java.util.EnumMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+public class Benefit {
+
+ private final Map<Event, Integer> details;
+
+ public Benefit() {
+ this.details = new EnumMap<>(Event.class);
+ initialBenefitDetails();
+ }
+
+ public int calculateTotalDiscount() {
+ return details.values()
+ .stream()
+ .reduce(0, Integer::sum);
+ }
+
+ public void addDiscountIntoDetails(Event event, int discount) {
+ details.computeIfPresent(event, (key, value) -> value + discount);
+ }
+
+ public String detailsToString() {
+ StringBuilder sb = new StringBuilder(Constant.NOTHING + System.lineSeparator());
+ if (calculateTotalDiscount() != 0) {
+ sb.setLength(0);
+ appendDetails(sb);
+ }
+ return sb.toString();
+ }
+
+ public int calculatePresentationPrice() {
+ return details.get(Event.PRESENTATION);
+ }
+
+ public String presentationMenuToString() {
+ Event presentation = Event.PRESENTATION;
+ StringBuilder sb = new StringBuilder(Constant.NOTHING + System.lineSeparator());
+ int discount = details.get(presentation);
+ if (discount != 0) {
+ sb.setLength(0);
+ sb.append(presentation.getTarget());
+ sb.append(Constant.SPACE);
+ sb.append(String.format(Constant.MENU_UNIT, Math.abs(discount / Event.PRESENTATION.getDiscount())));
+ sb.append(System.lineSeparator());
+ }
+ return sb.toString();
+ }
+
+
+ private void appendDetails(StringBuilder benefitDetail) {
+ for (Entry<Event, Integer> entry : details.entrySet()) {
+ String eventMessage = entry.getKey().getMessage();
+ int discount = entry.getValue();
+ if (discount != 0) {
+ benefitDetail.append(eventMessage);
+ benefitDetail.append(Constant.SPACE);
+ benefitDetail.append(String.format(Constant.PRICE_UNIT, discount));
+ benefitDetail.append(System.lineSeparator());
+ }
+ }
+ }
+
+ private void initialBenefitDetails() {
+ Event.getAllEvent().forEach(event -> details.put(event, 0));
+ }
+
+} | Java | add ๋ฉ์๋๋ฅผ ๊ตฌํํ๋ ๊ฒ๋ณด๋ค๋ ์์ฑ์์์ ์์ฑ๋ EnumMap์ ๋ฐ๋ ๊ฒ ์ข์ ๊ฒ ๊ฐ์์.
add ๋ฉ์๋๋ฅผ ์ด์ฉํด์ EnumMap์ ๋ง๋๋ ์ฑ
์์ BenefitBuilder ๊ฐ์ฒด๋ฅผ ์๋ก ๋ง๋ค์ด์ ๋งก๊ธฐ๋ ๊ฒ ์ข์์. |
@@ -0,0 +1,83 @@
+package christmas.service;
+
+import christmas.constant.Constant;
+import christmas.domain.Badge;
+import christmas.domain.Benefit;
+import christmas.domain.Event;
+import christmas.domain.OrderMenu;
+import christmas.view.input.template.InputCallback;
+import christmas.view.input.template.InputTemplate;
+
+public class ChristmasService {
+
+ private final InputTemplate inputTemplate;
+
+ public ChristmasService() {
+ this.inputTemplate = new InputTemplate();
+ }
+
+ public <T> T getInputRequestResult(InputCallback<T> callback) {
+ return inputTemplate.execute(callback);
+ }
+
+ public Benefit getBenefit(OrderMenu orderMenu, int day) {
+ Benefit benefit = new Benefit();
+ addDiscountIntoBenefitDetails(orderMenu, benefit, day);
+ return benefit;
+ }
+
+ public String getOrderMenuDetails(OrderMenu orderMenu) {
+ return orderMenu.detailsToString();
+ }
+
+ public String getTotalPriceBeforeDiscount(OrderMenu orderMenu) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), orderMenu.calculateTotalPrice());
+ }
+
+ public String getPresentationMenu(Benefit benefit) {
+ return benefit.presentationMenuToString();
+ }
+
+ public String getBenefitDetails(Benefit benefit) {
+ return benefit.detailsToString();
+ }
+
+ public String getTotalDiscount(Benefit benefit) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), benefit.calculateTotalDiscount());
+ }
+
+ public String getTotalPriceAfterDiscount(OrderMenu orderMenu, Benefit benefit) {
+ int totalPrice = orderMenu.calculateTotalPrice();
+ int totalDiscount = benefit.calculateTotalDiscount();
+ totalPrice += (totalDiscount - benefit.calculatePresentationPrice());
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), totalPrice);
+ }
+
+ public String getBadge(Benefit benefit) {
+ return Badge.findByTotalDiscount(benefit.calculateTotalDiscount());
+ }
+
+
+ private void addDiscountIntoBenefitDetails(OrderMenu orderMenu, Benefit benefit, int day) {
+ Event.findAllByDay(day)
+ .stream()
+ .filter(event -> orderMenu.calculateTotalPrice() > event.getCondition())
+ .forEach(event -> benefit.addDiscountIntoDetails(event, calculateDiscount(orderMenu, event, day)));
+ }
+
+ private int calculateDiscount(OrderMenu orderMenu, Event event, int day) {
+ int result = 0;
+ int orderMenuCount = orderMenu.countMenuByEventTarget(event.getTarget());
+ int discount = event.getDiscount();
+ int discountFromTotal = event.getDiscountFromTotal();
+ result -= (discount * orderMenuCount) + discountFromTotal;
+
+ if (event == Event.CHRISTMAS && day <= 25) {
+ result -= discount * (day - 1) + 1000;
+ }
+ if (event == Event.PRESENTATION) {
+ result -= discount;
+ }
+ return result;
+ }
+} | Java | benefit init์ ํด์ผ ํ๋ค๋ฉด, ์ธ๋ถ์์ ๋ฐ์์ค๋ ๊ฒ๋ณด๋ค๋ ๋ด๋ถ์์ benefit๋ฅผ ์์ฑํ๊ณ ๋ฐํํ๊ฒ ํ๋ ๊ฒ ์ข์์. ์ธ๋ถ์์ ๋ฐ์์จ benefit์ ๋ํด ์์
์ ์งํํ๋ฉด side effect๊ฐ ๋ฐ์ํ ์ฌ์ง๊ฐ ๋์์.
ํด๋น ์ฝ๋๋ ๋ฉ์๋๋ก ๋ถ๋ฆฌํ์ง ์๋ ๊ฒ ์ข์์ ๊ฒ ๊ฐ์์.
๋น๋๋ฅผ ํ์ฉํ๋ฉด ๋ ์ข์ต๋๋ค :DD |
@@ -0,0 +1,83 @@
+package christmas.service;
+
+import christmas.constant.Constant;
+import christmas.domain.Badge;
+import christmas.domain.Benefit;
+import christmas.domain.Event;
+import christmas.domain.OrderMenu;
+import christmas.view.input.template.InputCallback;
+import christmas.view.input.template.InputTemplate;
+
+public class ChristmasService {
+
+ private final InputTemplate inputTemplate;
+
+ public ChristmasService() {
+ this.inputTemplate = new InputTemplate();
+ }
+
+ public <T> T getInputRequestResult(InputCallback<T> callback) {
+ return inputTemplate.execute(callback);
+ }
+
+ public Benefit getBenefit(OrderMenu orderMenu, int day) {
+ Benefit benefit = new Benefit();
+ addDiscountIntoBenefitDetails(orderMenu, benefit, day);
+ return benefit;
+ }
+
+ public String getOrderMenuDetails(OrderMenu orderMenu) {
+ return orderMenu.detailsToString();
+ }
+
+ public String getTotalPriceBeforeDiscount(OrderMenu orderMenu) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), orderMenu.calculateTotalPrice());
+ }
+
+ public String getPresentationMenu(Benefit benefit) {
+ return benefit.presentationMenuToString();
+ }
+
+ public String getBenefitDetails(Benefit benefit) {
+ return benefit.detailsToString();
+ }
+
+ public String getTotalDiscount(Benefit benefit) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), benefit.calculateTotalDiscount());
+ }
+
+ public String getTotalPriceAfterDiscount(OrderMenu orderMenu, Benefit benefit) {
+ int totalPrice = orderMenu.calculateTotalPrice();
+ int totalDiscount = benefit.calculateTotalDiscount();
+ totalPrice += (totalDiscount - benefit.calculatePresentationPrice());
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), totalPrice);
+ }
+
+ public String getBadge(Benefit benefit) {
+ return Badge.findByTotalDiscount(benefit.calculateTotalDiscount());
+ }
+
+
+ private void addDiscountIntoBenefitDetails(OrderMenu orderMenu, Benefit benefit, int day) {
+ Event.findAllByDay(day)
+ .stream()
+ .filter(event -> orderMenu.calculateTotalPrice() > event.getCondition())
+ .forEach(event -> benefit.addDiscountIntoDetails(event, calculateDiscount(orderMenu, event, day)));
+ }
+
+ private int calculateDiscount(OrderMenu orderMenu, Event event, int day) {
+ int result = 0;
+ int orderMenuCount = orderMenu.countMenuByEventTarget(event.getTarget());
+ int discount = event.getDiscount();
+ int discountFromTotal = event.getDiscountFromTotal();
+ result -= (discount * orderMenuCount) + discountFromTotal;
+
+ if (event == Event.CHRISTMAS && day <= 25) {
+ result -= discount * (day - 1) + 1000;
+ }
+ if (event == Event.PRESENTATION) {
+ result -= discount;
+ }
+ return result;
+ }
+} | Java | ํ ์ธ์ก์ ๊ณ์ฐํ๋ ๋ก์ง์ด ์ธ๋ถ๋ก ๋
ธ์ถ๋์ด ์์ด์.
enum์ ํ์ฉํ์
จ์ผ๋ ์ ๋ค๋ฌ์ผ๋ฉด ์ด๋ ๊ฒ ๋ฐ๊ฟ ์ ์์ด์.
```suggestion
private int calculateDiscount(OrderMenu orderMenu, Event event, int day) {
return event.calculateDiscount(orderMenu, day);
}
```
์ด๋ฌ๋ฉด ๋ฉ์๋๋ก ๋ถ๋ฆฌํ ํ์๋ ์์ด์ง๊ณ ์ข์์.
์ด๋ฒคํธ enum๋ง๋ค ๋๋ค์์ ์์ฑํด์ ํํ์ก์ ๊ณ์ฐํด๋ณด์ธ์. |
@@ -0,0 +1,83 @@
+package christmas.service;
+
+import christmas.constant.Constant;
+import christmas.domain.Badge;
+import christmas.domain.Benefit;
+import christmas.domain.Event;
+import christmas.domain.OrderMenu;
+import christmas.view.input.template.InputCallback;
+import christmas.view.input.template.InputTemplate;
+
+public class ChristmasService {
+
+ private final InputTemplate inputTemplate;
+
+ public ChristmasService() {
+ this.inputTemplate = new InputTemplate();
+ }
+
+ public <T> T getInputRequestResult(InputCallback<T> callback) {
+ return inputTemplate.execute(callback);
+ }
+
+ public Benefit getBenefit(OrderMenu orderMenu, int day) {
+ Benefit benefit = new Benefit();
+ addDiscountIntoBenefitDetails(orderMenu, benefit, day);
+ return benefit;
+ }
+
+ public String getOrderMenuDetails(OrderMenu orderMenu) {
+ return orderMenu.detailsToString();
+ }
+
+ public String getTotalPriceBeforeDiscount(OrderMenu orderMenu) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), orderMenu.calculateTotalPrice());
+ }
+
+ public String getPresentationMenu(Benefit benefit) {
+ return benefit.presentationMenuToString();
+ }
+
+ public String getBenefitDetails(Benefit benefit) {
+ return benefit.detailsToString();
+ }
+
+ public String getTotalDiscount(Benefit benefit) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), benefit.calculateTotalDiscount());
+ }
+
+ public String getTotalPriceAfterDiscount(OrderMenu orderMenu, Benefit benefit) {
+ int totalPrice = orderMenu.calculateTotalPrice();
+ int totalDiscount = benefit.calculateTotalDiscount();
+ totalPrice += (totalDiscount - benefit.calculatePresentationPrice());
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), totalPrice);
+ }
+
+ public String getBadge(Benefit benefit) {
+ return Badge.findByTotalDiscount(benefit.calculateTotalDiscount());
+ }
+
+
+ private void addDiscountIntoBenefitDetails(OrderMenu orderMenu, Benefit benefit, int day) {
+ Event.findAllByDay(day)
+ .stream()
+ .filter(event -> orderMenu.calculateTotalPrice() > event.getCondition())
+ .forEach(event -> benefit.addDiscountIntoDetails(event, calculateDiscount(orderMenu, event, day)));
+ }
+
+ private int calculateDiscount(OrderMenu orderMenu, Event event, int day) {
+ int result = 0;
+ int orderMenuCount = orderMenu.countMenuByEventTarget(event.getTarget());
+ int discount = event.getDiscount();
+ int discountFromTotal = event.getDiscountFromTotal();
+ result -= (discount * orderMenuCount) + discountFromTotal;
+
+ if (event == Event.CHRISTMAS && day <= 25) {
+ result -= discount * (day - 1) + 1000;
+ }
+ if (event == Event.PRESENTATION) {
+ result -= discount;
+ }
+ return result;
+ }
+} | Java | ์ด๋ฐ ์๋ช
ํ ์ฝ๋๋ค์ ๋ฉ์๋๋ก ๋ถ๋ฆฌํ ํ์๊ฐ ์์ด์. ์๋น์ค ๊ฐ์ฒด๊น์ง ์ด์ฉํ ํ์๋ ๋๋์ฑ ์์ด์. |
@@ -0,0 +1,58 @@
+package christmas.constant;
+
+import christmas.constant.MenuConstant.MenuType;
+import christmas.domain.Menu;
+import java.util.List;
+
+public class EventConstant {
+ public static class Condition {
+
+ public static final int CASE_A = 10000;
+ public static final int CASE_B = 120000;
+ }
+
+ public static class Days {
+
+ public static final List<Integer> EVERY = List.of(1, 2, 3, 4, 5, 6);
+ public static final List<Integer> WEEKDAY = List.of(0, 3, 4, 5, 6);
+ public static final List<Integer> WEEKEND = List.of(1, 2);
+ public static final List<Integer> SPECIAL = List.of(3, 25);
+
+ }
+
+ public static class Target {
+
+ public static final String WEEKDAY = MenuType.DESSERT;
+ public static final String WEEKEND = MenuType.MAIN;
+ public static final String CHRISTMAS = MenuType.NONE;
+ public static final String SPECIAL = MenuType.NONE;
+ public static final String PRESENTATION = Menu.CHAMPAGNE.getName();
+
+ }
+
+ public static class Discount {
+
+ public static final int WEEKDAY = 2023;
+ public static final int WEEKEND = 2023;
+ public static final int CHRISTMAS = 100;
+ public static final int SPECIAL = 0;
+ public static final int PRESENTATION = Menu.CHAMPAGNE.getPrice() * 1;
+
+ }
+
+ public static class TotalDiscount {
+ public static final int SPECIAL = 1000;
+ public static final int OTHER = 0;
+ }
+
+ public static class Message {
+
+ public static final String SPECIAL = "ํน๋ณ ํ ์ธ:";
+ public static final String WEEKDAY = "ํ์ผ ํ ์ธ:";
+ public static final String WEEKEND = "์ฃผ๋ง ํ ์ธ:";
+ public static final String CHRISTMAS = "ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ:";
+ public static final String PRESENTATION = "์ฆ์ ์ด๋ฒคํธ:";
+
+ }
+
+} | Java | ์ด๊ฒ ๋ฌด์จ ์์์ธ์ง ์ ์๊ฐ ์์ด์. ์ด๋ฆ์ ๋ช
ํํ ์ง์ด์ฃผ์ธ์.
์์ด๊ฐ ์๋ง์ด๋๋ผ๋ EventAvailablePrice ๊ฐ์ ์์ผ๋ก ์ ์ด์ฃผ์ธ์. |
@@ -0,0 +1,72 @@
+package christmas.domain;
+
+import christmas.constant.Constant;
+import java.util.EnumMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+public class Benefit {
+
+ private final Map<Event, Integer> details;
+
+ public Benefit() {
+ this.details = new EnumMap<>(Event.class);
+ initialBenefitDetails();
+ }
+
+ public int calculateTotalDiscount() {
+ return details.values()
+ .stream()
+ .reduce(0, Integer::sum);
+ }
+
+ public void addDiscountIntoDetails(Event event, int discount) {
+ details.computeIfPresent(event, (key, value) -> value + discount);
+ }
+
+ public String detailsToString() {
+ StringBuilder sb = new StringBuilder(Constant.NOTHING + System.lineSeparator());
+ if (calculateTotalDiscount() != 0) {
+ sb.setLength(0);
+ appendDetails(sb);
+ }
+ return sb.toString();
+ }
+
+ public int calculatePresentationPrice() {
+ return details.get(Event.PRESENTATION);
+ }
+
+ public String presentationMenuToString() {
+ Event presentation = Event.PRESENTATION;
+ StringBuilder sb = new StringBuilder(Constant.NOTHING + System.lineSeparator());
+ int discount = details.get(presentation);
+ if (discount != 0) {
+ sb.setLength(0);
+ sb.append(presentation.getTarget());
+ sb.append(Constant.SPACE);
+ sb.append(String.format(Constant.MENU_UNIT, Math.abs(discount / Event.PRESENTATION.getDiscount())));
+ sb.append(System.lineSeparator());
+ }
+ return sb.toString();
+ }
+
+
+ private void appendDetails(StringBuilder benefitDetail) {
+ for (Entry<Event, Integer> entry : details.entrySet()) {
+ String eventMessage = entry.getKey().getMessage();
+ int discount = entry.getValue();
+ if (discount != 0) {
+ benefitDetail.append(eventMessage);
+ benefitDetail.append(Constant.SPACE);
+ benefitDetail.append(String.format(Constant.PRICE_UNIT, discount));
+ benefitDetail.append(System.lineSeparator());
+ }
+ }
+ }
+
+ private void initialBenefitDetails() {
+ Event.getAllEvent().forEach(event -> details.put(event, 0));
+ }
+
+} | Java | StringBuilder๋ฅผ ์ธ๋ถ์์ ๋ฐ์์์ผ ํ๋ ์ด์ ๊ฐ ์์์๊น์?
์๋๋ผ๋ฉด ๋ด๋ถ์์ StringBuilder๋ฅผ ์์ฑํด์ ์ฌ์ฉํ์ธ์.
๊ผญ ์ธ๋ถ์์ StringBuilder๋ฅผ ๋ฐ์์์ผ๋ง ํ๋ ๊ฒฝ์ฐ๋ผ๋ฉด, ์ค๊ณ๊ฐ ์๋ชป๋ ๊ฑฐ์์. |
@@ -0,0 +1,106 @@
+package christmas.domain;
+
+
+import christmas.constant.Constant;
+import christmas.constant.ErrorMessage;
+import christmas.constant.MenuConstant.MenuType;
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+public class OrderMenu {
+
+ private final Map<Menu, Integer> details;
+
+ public OrderMenu(List<String> menus) {
+ validateMenus(menus);
+ this.details = createDetail(menus);
+ }
+
+ public String detailsToString() {
+ StringBuilder sb = new StringBuilder();
+ for (Entry<Menu, Integer> entry : details.entrySet()) {
+ sb.append(entry.getKey().getName());
+ sb.append(Constant.SPACE);
+ sb.append(String.format(Constant.MENU_UNIT, entry.getValue()));
+ sb.append(System.lineSeparator());
+ }
+ return sb.toString();
+ }
+
+ public int calculateTotalPrice() {
+ return details.entrySet()
+ .stream()
+ .mapToInt(entry -> entry.getKey().getPrice() * entry.getValue())
+ .sum();
+ }
+
+ public int countMenuByEventTarget(String eventTarget) {
+ return details.entrySet()
+ .stream()
+ .filter(entry -> entry.getKey().getType().equals(eventTarget))
+ .mapToInt(Entry::getValue)
+ .sum();
+ }
+
+ private Map<Menu, Integer> createDetail(List<String> menus) {
+ Map<Menu, Integer> detail = new EnumMap<>(Menu.class);
+ for (String menu : menus) {
+ putMenuIntoDetail(menu, detail);
+ }
+ return detail;
+ }
+
+ private void putMenuIntoDetail(String menu, Map<Menu, Integer> detail) {
+ String[] menuAndQuantity = menu.split(Constant.DELIMITER_HYPHEN);
+ detail.put(Menu.findByName(menuAndQuantity[0]), Integer.parseInt(menuAndQuantity[1]));
+ }
+
+ private void validateMenus(List<String> menus) {
+ if (isDuplicate(menus) || isNothing(menus)) {
+ throw new IllegalArgumentException(ErrorMessage.WRONG_MENU);
+ }
+ validateQuantity(menus);
+ validateOnlyBeverage(menus);
+ }
+
+ private boolean isNothing(List<String> menus) {
+ return menus.stream()
+ .map(menu -> menu.substring(0, menu.indexOf(Constant.DELIMITER_HYPHEN)))
+ .anyMatch(menu -> !Menu.isExistByName(menu));
+ }
+
+ private boolean isDuplicate(List<String> menus) {
+ return menus.stream()
+ .map(menu -> menu.substring(0, menu.indexOf(Constant.DELIMITER_HYPHEN)))
+ .distinct()
+ .count() != menus.size();
+ }
+
+ private void validateQuantity(List<String> menus) {
+ if (calculateQuantity(menus) > Constant.MENU_MAXIMUM_QUANTITY) {
+ throw new IllegalArgumentException(ErrorMessage.QUANTITY_OVER);
+ }
+ }
+
+ private int calculateQuantity(List<String> menus) {
+ return menus.stream()
+ .map(menu -> menu.split(Constant.DELIMITER_HYPHEN)[1])
+ .map(Integer::parseInt)
+ .reduce(0, Integer::sum);
+ }
+
+ private void validateOnlyBeverage(List<String> menus) {
+ if (isOnlyBeverage(menus)) {
+ throw new IllegalArgumentException(ErrorMessage.ONLY_DRINK);
+ }
+ }
+
+ private boolean isOnlyBeverage(List<String> menus) {
+ return menus.stream()
+ .map(menu -> menu.substring(0, menu.indexOf(Constant.DELIMITER_HYPHEN)))
+ .allMatch(menu -> Menu.findByName(menu).getType().equals(MenuType.DRINK));
+ }
+
+} | Java | ๋ฑํ ์ค์ํ ๋ถ๋ถ์ ์๋๋ฐ, ์๋ก ์ฐ๊ด๋ ๋ฉ์๋๋ผ๋ฆฌ ๊ฐ๊น์ด ๋ถ์ด ์๋๋ก ์ฝ๋๋ฅผ ์ ๋ฆฌํด์ฃผ๋ ๊ฒ ์ข์์.
๋ฉ์๋ ์์๊ฐ ๊ผฌ์ฌ ์์ผ๋ฉด ๋ฆฌ๋ทฐํ๋ ์
์ฅ์์ ๊ฝค ํ๋ค์ด์. |
@@ -0,0 +1,14 @@
+package christmas.constant;
+
+public class MenuConstant {
+
+ public static class MenuType {
+
+ public static final String APPETIZER = "appetizer";
+ public static final String MAIN = "main";
+ public static final String DESSERT = "dessert";
+ public static final String DRINK = "drink";
+ public static final String NONE = "none";
+
+ }
+} | Java | enum์ APPETIZER, MAIN, DESSERT, DRINK๋ง ์ ์ผ์
๋ ๋์ ๊ฒ ๊ฐ์์. string ์์๊ฐ ์ด์ฉ๋๋ ๊ฑธ ๋ณด์ง ๋ชปํ์ด์. |
@@ -0,0 +1,103 @@
+package christmas.domain;
+
+import christmas.constant.EventConstant.Condition;
+import christmas.constant.EventConstant.Days;
+import christmas.constant.EventConstant.Discount;
+import christmas.constant.EventConstant.Message;
+import christmas.constant.EventConstant.Target;
+import christmas.constant.EventConstant.TotalDiscount;
+import java.util.Arrays;
+import java.util.List;
+
+public enum Event {
+
+ /*
+ index0(Condition): ์ด ์ฃผ๋ฌธ ๊ธ์ก ์กฐ๊ฑด
+ index1(Days): ์ ์ฉ ๋ ์ง
+ index2(Target): ํ ์ธ ๋ฉ๋ด ๋๋ ์ฆ์ ํ
+ index3(Discount): ํ ์ธ ๊ธ์ก
+ index4(DiscountFromTotal): ์ด๊ธ์ก์์ ํ ์ธ ๊ธ์ก
+ index5(Message): ํ ์ธ ๋ฉ์์ง (e.g. WEEKDAY -> "ํ์ผ ํ ์ธ:")
+ */
+ SPECIAL(Condition.CASE_A,
+ Days.SPECIAL,
+ Target.SPECIAL,
+ Discount.SPECIAL,
+ TotalDiscount.SPECIAL,
+ Message.SPECIAL),
+
+ WEEKDAY(Condition.CASE_A,
+ Days.WEEKDAY,
+ Target.WEEKDAY,
+ Discount.WEEKDAY,
+ TotalDiscount.OTHER,
+ Message.WEEKDAY),
+
+ WEEKEND(Condition.CASE_A,
+ Days.WEEKEND,
+ Target.WEEKEND,
+ Discount.WEEKEND,
+ TotalDiscount.OTHER,
+ Message.WEEKEND),
+
+ CHRISTMAS(Condition.CASE_A,
+ Days.EVERY,
+ Target.CHRISTMAS,
+ Discount.CHRISTMAS,
+ TotalDiscount.OTHER,
+ Message.CHRISTMAS),
+
+ PRESENTATION(Condition.CASE_B,
+ Days.EVERY,
+ Target.PRESENTATION,
+ Discount.PRESENTATION,
+ TotalDiscount.OTHER,
+ Message.PRESENTATION);
+
+
+ private final int condition;
+ private final List<Integer> days;
+ private final String target;
+ private final int discount;
+ private final int discountFromTotal;
+ private final String message;
+
+ Event(int condition, List<Integer> days, String target, int discountMenu, int discountTotal, String message) {
+ this.condition = condition;
+ this.days = days;
+ this.target = target;
+ this.discount = discountMenu;
+ this.discountFromTotal = discountTotal;
+ this.message = message;
+ }
+
+ public static List<Event> findAllByDay(int day) {
+ return Arrays.stream(Event.values())
+ .filter(event -> event.days.contains(day) || event.days.contains(day % 7))
+ .toList();
+ }
+
+ public static List<Event> getAllEvent() {
+ return Arrays.stream(Event.values()).toList();
+ }
+
+ public int getDiscount() {
+ return discount;
+ }
+
+ public int getDiscountFromTotal() {
+ return discountFromTotal;
+ }
+
+ public String getTarget() {
+ return target;
+ }
+
+ public int getCondition() {
+ return condition;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+} | Java | ๋ด๋ถ ๊ฐ๊ณผ ๊ตฌํ์ด ๋ฟ๋ฟ์ด ํฉ์ด์ ธ ์๋ค์...
๋ณต์กํ์ง ์๋ค๋ฉด, enum ํ๋์ ์ ๋ถ ๋ฃ์ด์ฃผ์ธ์. ์ด๋ ๊ฒ ๋ง๋ค๋ฉด ์ ์ง๋ณด์๊ฐ ๋ ํ๋ค์ด์ ธ์. |
@@ -0,0 +1,65 @@
+package christmas.domain;
+
+import christmas.constant.MenuConstant.MenuType;
+import java.util.Arrays;
+
+public enum Menu {
+
+ //์ ํผํ์ด์
+ MUSHROOM_SOUP(MenuType.APPETIZER, "์์ก์ด์ํ", 6_000),
+ TAPAS(MenuType.APPETIZER, "ํํ์ค", 5_500),
+ CAESAR_SALAD(MenuType.APPETIZER, "์์ ์๋ฌ๋", 8_000),
+
+ //๋ฉ์ธ
+ T_BONE_STEAK(MenuType.MAIN, "ํฐ๋ณธ์คํ
์ดํฌ", 55_000),
+ BBQ_RIBS(MenuType.MAIN, "๋ฐ๋นํ๋ฆฝ", 54_000),
+ SEAFOOD_PASTA(MenuType.MAIN, "ํด์ฐ๋ฌผํ์คํ", 35_000),
+ CHRISTMAS_PASTA(MenuType.MAIN, "ํฌ๋ฆฌ์ค๋ง์คํ์คํ", 25_000),
+
+ //๋์ ํธ
+ CHOCOLATE_CAKE(MenuType.DESSERT, "์ด์ฝ์ผ์ดํฌ", 15_000),
+ ICE_CREAM(MenuType.DESSERT, "์์ด์คํฌ๋ฆผ", 5_000),
+
+ //์๋ฃ
+ ZERO_COKE(MenuType.DRINK, "์ ๋ก์ฝ๋ผ", 3_000),
+ RED_WINE(MenuType.DRINK, "๋ ๋์์ธ", 60_000),
+ CHAMPAGNE(MenuType.DRINK, "์ดํ์ธ", 25_000),
+
+ //NONE
+ NONE(MenuType.NONE, "์๋๋ฉ๋ด", 0);
+
+ private final String type;
+ private final String name;
+ private final int price;
+
+ Menu(String type, String name, int price) {
+ this.type = type;
+ this.name = name;
+ this.price = price;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public static Menu findByName(String menuName) {
+ return Arrays.stream(Menu.values())
+ .filter(menu -> menu.getName().equals(menuName))
+ .findFirst()
+ .orElse(NONE);
+ }
+
+ public static boolean isExistByName(String menuName) {
+ return Arrays.stream(Menu.values())
+ .anyMatch(menu -> menu.getName().equals(menuName));
+ }
+
+} | Java | ์ด ์ฝ๋๋ ๊น๋ํ๊ฒ ์ ์์ฑํ์
จ๋ค์. ๐ |
@@ -0,0 +1,30 @@
+package christmas.domain;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertAll;
+
+import java.util.List;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+class EventTest {
+
+ @DisplayName("๋ ์ง์ ํด๋นํ๋ ๋ชจ๋ ์ด๋ฒคํธ๋ค์ ์ฐพ๋๋ค.")
+ @Test
+ void findAllByDay() throws Exception {
+ //given
+ int day = 3;
+ //when
+ List<Event> events = Event.findAllByDay(3);
+ //then
+ assertAll(
+
+ () -> assertThat(events).contains(Event.WEEKDAY),
+ () -> assertThat(events).contains(Event.CHRISTMAS),
+ () -> assertThat(events).contains(Event.SPECIAL),
+ () -> assertThat(events).contains(Event.PRESENTATION)
+ );
+ }
+
+
+}
\ No newline at end of file | Java | ํ
์คํธ ์ฝ๋๋ผ ํด๋ ๋งค์ง ๋๋ฒ๋ฅผ ์ ๊ฑฐํด์ฃผ๋ฉด ์ข์์ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,83 @@
+package christmas.service;
+
+import christmas.constant.Constant;
+import christmas.domain.Badge;
+import christmas.domain.Benefit;
+import christmas.domain.Event;
+import christmas.domain.OrderMenu;
+import christmas.view.input.template.InputCallback;
+import christmas.view.input.template.InputTemplate;
+
+public class ChristmasService {
+
+ private final InputTemplate inputTemplate;
+
+ public ChristmasService() {
+ this.inputTemplate = new InputTemplate();
+ }
+
+ public <T> T getInputRequestResult(InputCallback<T> callback) {
+ return inputTemplate.execute(callback);
+ }
+
+ public Benefit getBenefit(OrderMenu orderMenu, int day) {
+ Benefit benefit = new Benefit();
+ addDiscountIntoBenefitDetails(orderMenu, benefit, day);
+ return benefit;
+ }
+
+ public String getOrderMenuDetails(OrderMenu orderMenu) {
+ return orderMenu.detailsToString();
+ }
+
+ public String getTotalPriceBeforeDiscount(OrderMenu orderMenu) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), orderMenu.calculateTotalPrice());
+ }
+
+ public String getPresentationMenu(Benefit benefit) {
+ return benefit.presentationMenuToString();
+ }
+
+ public String getBenefitDetails(Benefit benefit) {
+ return benefit.detailsToString();
+ }
+
+ public String getTotalDiscount(Benefit benefit) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), benefit.calculateTotalDiscount());
+ }
+
+ public String getTotalPriceAfterDiscount(OrderMenu orderMenu, Benefit benefit) {
+ int totalPrice = orderMenu.calculateTotalPrice();
+ int totalDiscount = benefit.calculateTotalDiscount();
+ totalPrice += (totalDiscount - benefit.calculatePresentationPrice());
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), totalPrice);
+ }
+
+ public String getBadge(Benefit benefit) {
+ return Badge.findByTotalDiscount(benefit.calculateTotalDiscount());
+ }
+
+
+ private void addDiscountIntoBenefitDetails(OrderMenu orderMenu, Benefit benefit, int day) {
+ Event.findAllByDay(day)
+ .stream()
+ .filter(event -> orderMenu.calculateTotalPrice() > event.getCondition())
+ .forEach(event -> benefit.addDiscountIntoDetails(event, calculateDiscount(orderMenu, event, day)));
+ }
+
+ private int calculateDiscount(OrderMenu orderMenu, Event event, int day) {
+ int result = 0;
+ int orderMenuCount = orderMenu.countMenuByEventTarget(event.getTarget());
+ int discount = event.getDiscount();
+ int discountFromTotal = event.getDiscountFromTotal();
+ result -= (discount * orderMenuCount) + discountFromTotal;
+
+ if (event == Event.CHRISTMAS && day <= 25) {
+ result -= discount * (day - 1) + 1000;
+ }
+ if (event == Event.PRESENTATION) {
+ result -= discount;
+ }
+ return result;
+ }
+} | Java | > ์์์ inputView์ ๋ฉ์๋๋ฅผ ๋๊ฒจ๋ฐ๊ณ ์คํํ๋ ๋ชจ์ต์ด๋๋ฐ, ๊ทธ๋ฅ ChristmasController์์ ์งํํ๋ ๊ฒ ์ข์์ ๊ฒ ๊ฐ์์. ๊ตณ์ด ์๋น์ค๊น์ง ๊ฑธ์น ํ์๊ฐ ์์์ ๊ฒ ๊ฐ์์. ์๋น์ค ๊ฐ์ฒด ๋ด์์ ํด๋น ๋ฉ์๋๊ฐ ์ฐ์ธ ๊ฒ๋ ์๋๊ณ , ์ค๋ก์ง ์ปจํธ๋กค๋ฌ์์๋ง ์ด ๋ฉ์๋๊ฐ ํธ์ถ๋๊ณ ์์ด์.
์ ๋ฉ์๋๋ ๋ง์ํ์ ๋๋ก Controller์ ์์ด๋ ๋ฌด๋ฐฉํ๊ธด ํฉ๋๋ค :)
ํ์ง๋ง Controller๊ฐ View, Service์ธ์ ๋ค๋ฅธ ๊ฐ์ฒด์ ์์กดํ์ง ์๊ฒ๋ InputTemplate๋ฅผ Service์ ๋๊ฑฐ์์ต๋๋ค! |
@@ -0,0 +1,72 @@
+package christmas.domain;
+
+import christmas.constant.Constant;
+import java.util.EnumMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+public class Benefit {
+
+ private final Map<Event, Integer> details;
+
+ public Benefit() {
+ this.details = new EnumMap<>(Event.class);
+ initialBenefitDetails();
+ }
+
+ public int calculateTotalDiscount() {
+ return details.values()
+ .stream()
+ .reduce(0, Integer::sum);
+ }
+
+ public void addDiscountIntoDetails(Event event, int discount) {
+ details.computeIfPresent(event, (key, value) -> value + discount);
+ }
+
+ public String detailsToString() {
+ StringBuilder sb = new StringBuilder(Constant.NOTHING + System.lineSeparator());
+ if (calculateTotalDiscount() != 0) {
+ sb.setLength(0);
+ appendDetails(sb);
+ }
+ return sb.toString();
+ }
+
+ public int calculatePresentationPrice() {
+ return details.get(Event.PRESENTATION);
+ }
+
+ public String presentationMenuToString() {
+ Event presentation = Event.PRESENTATION;
+ StringBuilder sb = new StringBuilder(Constant.NOTHING + System.lineSeparator());
+ int discount = details.get(presentation);
+ if (discount != 0) {
+ sb.setLength(0);
+ sb.append(presentation.getTarget());
+ sb.append(Constant.SPACE);
+ sb.append(String.format(Constant.MENU_UNIT, Math.abs(discount / Event.PRESENTATION.getDiscount())));
+ sb.append(System.lineSeparator());
+ }
+ return sb.toString();
+ }
+
+
+ private void appendDetails(StringBuilder benefitDetail) {
+ for (Entry<Event, Integer> entry : details.entrySet()) {
+ String eventMessage = entry.getKey().getMessage();
+ int discount = entry.getValue();
+ if (discount != 0) {
+ benefitDetail.append(eventMessage);
+ benefitDetail.append(Constant.SPACE);
+ benefitDetail.append(String.format(Constant.PRICE_UNIT, discount));
+ benefitDetail.append(System.lineSeparator());
+ }
+ }
+ }
+
+ private void initialBenefitDetails() {
+ Event.getAllEvent().forEach(event -> details.put(event, 0));
+ }
+
+} | Java | > add ๋ฉ์๋๋ฅผ ๊ตฌํํ๋ ๊ฒ๋ณด๋ค๋ ์์ฑ์์์ ์์ฑ๋ EnumMap์ ๋ฐ๋ ๊ฒ ์ข์ ๊ฒ ๊ฐ์์. add ๋ฉ์๋๋ฅผ ์ด์ฉํด์ EnumMap์ ๋ง๋๋ ์ฑ
์์ BenefitBuilder ๊ฐ์ฒด๋ฅผ ์๋ก ๋ง๋ค์ด์ ๋งก๊ธฐ๋ ๊ฒ ์ข์์.
๊ทธ๋ ๊ฒ ๋ค์! ๋น๋๋ฅผ ์ฌ์ฉํ๋ฉด ์ถํ ์๋ชป๋ Benfit ๊ฒฐ๊ณผ๊ฐ ๋์์๋ ํฌ๋ก์ค์ฒดํฌํ๊ธฐ๋ ์ฉ์ดํ๊ฒ ๋ค์ ! ์ข์ ํผ๋๋ฐฑ ๊ฐ์ฌํฉ๋๋ค ใ
ใ
|
@@ -0,0 +1,83 @@
+package christmas.service;
+
+import christmas.constant.Constant;
+import christmas.domain.Badge;
+import christmas.domain.Benefit;
+import christmas.domain.Event;
+import christmas.domain.OrderMenu;
+import christmas.view.input.template.InputCallback;
+import christmas.view.input.template.InputTemplate;
+
+public class ChristmasService {
+
+ private final InputTemplate inputTemplate;
+
+ public ChristmasService() {
+ this.inputTemplate = new InputTemplate();
+ }
+
+ public <T> T getInputRequestResult(InputCallback<T> callback) {
+ return inputTemplate.execute(callback);
+ }
+
+ public Benefit getBenefit(OrderMenu orderMenu, int day) {
+ Benefit benefit = new Benefit();
+ addDiscountIntoBenefitDetails(orderMenu, benefit, day);
+ return benefit;
+ }
+
+ public String getOrderMenuDetails(OrderMenu orderMenu) {
+ return orderMenu.detailsToString();
+ }
+
+ public String getTotalPriceBeforeDiscount(OrderMenu orderMenu) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), orderMenu.calculateTotalPrice());
+ }
+
+ public String getPresentationMenu(Benefit benefit) {
+ return benefit.presentationMenuToString();
+ }
+
+ public String getBenefitDetails(Benefit benefit) {
+ return benefit.detailsToString();
+ }
+
+ public String getTotalDiscount(Benefit benefit) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), benefit.calculateTotalDiscount());
+ }
+
+ public String getTotalPriceAfterDiscount(OrderMenu orderMenu, Benefit benefit) {
+ int totalPrice = orderMenu.calculateTotalPrice();
+ int totalDiscount = benefit.calculateTotalDiscount();
+ totalPrice += (totalDiscount - benefit.calculatePresentationPrice());
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), totalPrice);
+ }
+
+ public String getBadge(Benefit benefit) {
+ return Badge.findByTotalDiscount(benefit.calculateTotalDiscount());
+ }
+
+
+ private void addDiscountIntoBenefitDetails(OrderMenu orderMenu, Benefit benefit, int day) {
+ Event.findAllByDay(day)
+ .stream()
+ .filter(event -> orderMenu.calculateTotalPrice() > event.getCondition())
+ .forEach(event -> benefit.addDiscountIntoDetails(event, calculateDiscount(orderMenu, event, day)));
+ }
+
+ private int calculateDiscount(OrderMenu orderMenu, Event event, int day) {
+ int result = 0;
+ int orderMenuCount = orderMenu.countMenuByEventTarget(event.getTarget());
+ int discount = event.getDiscount();
+ int discountFromTotal = event.getDiscountFromTotal();
+ result -= (discount * orderMenuCount) + discountFromTotal;
+
+ if (event == Event.CHRISTMAS && day <= 25) {
+ result -= discount * (day - 1) + 1000;
+ }
+ if (event == Event.PRESENTATION) {
+ result -= discount;
+ }
+ return result;
+ }
+} | Java | > benefit init์ ํด์ผ ํ๋ค๋ฉด, ์ธ๋ถ์์ ๋ฐ์์ค๋ ๊ฒ๋ณด๋ค๋ ๋ด๋ถ์์ benefit๋ฅผ ์์ฑํ๊ณ ๋ฐํํ๊ฒ ํ๋ ๊ฒ ์ข์์. ์ธ๋ถ์์ ๋ฐ์์จ benefit์ ๋ํด ์์
์ ์งํํ๋ฉด side effect๊ฐ ๋ฐ์ํ ์ฌ์ง๊ฐ ๋์์. ํด๋น ์ฝ๋๋ ๋ฉ์๋๋ก ๋ถ๋ฆฌํ์ง ์๋ ๊ฒ ์ข์์ ๊ฒ ๊ฐ์์.
>
> ๋น๋๋ฅผ ํ์ฉํ๋ฉด ๋ ์ข์ต๋๋ค :DD
์ benefit์ ๋ฐํํ๋ค๋๊ฒ ํ๋์ ์๋ ๋ณ์๋ฅผ ๊ทธ๋๋ก ๋ฐํํด์ผํ๋ค๋ ๋ง์์ผ๊น์??! |
@@ -0,0 +1,83 @@
+package christmas.service;
+
+import christmas.constant.Constant;
+import christmas.domain.Badge;
+import christmas.domain.Benefit;
+import christmas.domain.Event;
+import christmas.domain.OrderMenu;
+import christmas.view.input.template.InputCallback;
+import christmas.view.input.template.InputTemplate;
+
+public class ChristmasService {
+
+ private final InputTemplate inputTemplate;
+
+ public ChristmasService() {
+ this.inputTemplate = new InputTemplate();
+ }
+
+ public <T> T getInputRequestResult(InputCallback<T> callback) {
+ return inputTemplate.execute(callback);
+ }
+
+ public Benefit getBenefit(OrderMenu orderMenu, int day) {
+ Benefit benefit = new Benefit();
+ addDiscountIntoBenefitDetails(orderMenu, benefit, day);
+ return benefit;
+ }
+
+ public String getOrderMenuDetails(OrderMenu orderMenu) {
+ return orderMenu.detailsToString();
+ }
+
+ public String getTotalPriceBeforeDiscount(OrderMenu orderMenu) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), orderMenu.calculateTotalPrice());
+ }
+
+ public String getPresentationMenu(Benefit benefit) {
+ return benefit.presentationMenuToString();
+ }
+
+ public String getBenefitDetails(Benefit benefit) {
+ return benefit.detailsToString();
+ }
+
+ public String getTotalDiscount(Benefit benefit) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), benefit.calculateTotalDiscount());
+ }
+
+ public String getTotalPriceAfterDiscount(OrderMenu orderMenu, Benefit benefit) {
+ int totalPrice = orderMenu.calculateTotalPrice();
+ int totalDiscount = benefit.calculateTotalDiscount();
+ totalPrice += (totalDiscount - benefit.calculatePresentationPrice());
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), totalPrice);
+ }
+
+ public String getBadge(Benefit benefit) {
+ return Badge.findByTotalDiscount(benefit.calculateTotalDiscount());
+ }
+
+
+ private void addDiscountIntoBenefitDetails(OrderMenu orderMenu, Benefit benefit, int day) {
+ Event.findAllByDay(day)
+ .stream()
+ .filter(event -> orderMenu.calculateTotalPrice() > event.getCondition())
+ .forEach(event -> benefit.addDiscountIntoDetails(event, calculateDiscount(orderMenu, event, day)));
+ }
+
+ private int calculateDiscount(OrderMenu orderMenu, Event event, int day) {
+ int result = 0;
+ int orderMenuCount = orderMenu.countMenuByEventTarget(event.getTarget());
+ int discount = event.getDiscount();
+ int discountFromTotal = event.getDiscountFromTotal();
+ result -= (discount * orderMenuCount) + discountFromTotal;
+
+ if (event == Event.CHRISTMAS && day <= 25) {
+ result -= discount * (day - 1) + 1000;
+ }
+ if (event == Event.PRESENTATION) {
+ result -= discount;
+ }
+ return result;
+ }
+} | Java | > ํ ์ธ์ก์ ๊ณ์ฐํ๋ ๋ก์ง์ด ์ธ๋ถ๋ก ๋
ธ์ถ๋์ด ์์ด์. enum์ ํ์ฉํ์
จ์ผ๋ ์ ๋ค๋ฌ์ผ๋ฉด ์ด๋ ๊ฒ ๋ฐ๊ฟ ์ ์์ด์.
>
> ์ด๋ฌ๋ฉด ๋ฉ์๋๋ก ๋ถ๋ฆฌํ ํ์๋ ์์ด์ง๊ณ ์ข์์. ์ด๋ฒคํธ enum๋ง๋ค ๋๋ค์์ ์์ฑํด์ ํํ์ก์ ๊ณ์ฐํด๋ณด์ธ์.
enum์ ๋๋ค์์ด ์์๋ก ๋ค์ด๊ฐ ์ ์๋ค๋๊ฑธ ํด๋ผ์ฐ๋๋ ์ฝ๋ ๋ณด๊ณ ์์์ต๋๋ค! ๋ง์ฝ enum ์์๋ค์ด ํ ์ธ๊ธ์ก์ ๊ณ์ฐํ ์ ์๋ ๋๋ค์์ ๊ฐ๊ณ ์์ผ๋ฉด if๋ฅผ ๋๋ฒ ์ฌ์ฉํ ์ผ๋ ์๊ฒ ๋ค์! ๋ง์ํด์ฃผ์ ํํธ๋ก ๋ฆฌํฉํ ๋ง ํ ๋ฒ ์งํํด๋ณผ๊ฒ์! ๊ฐ์ฌํฉ๋๋ค ใ
ใ
|
@@ -0,0 +1,83 @@
+package christmas.service;
+
+import christmas.constant.Constant;
+import christmas.domain.Badge;
+import christmas.domain.Benefit;
+import christmas.domain.Event;
+import christmas.domain.OrderMenu;
+import christmas.view.input.template.InputCallback;
+import christmas.view.input.template.InputTemplate;
+
+public class ChristmasService {
+
+ private final InputTemplate inputTemplate;
+
+ public ChristmasService() {
+ this.inputTemplate = new InputTemplate();
+ }
+
+ public <T> T getInputRequestResult(InputCallback<T> callback) {
+ return inputTemplate.execute(callback);
+ }
+
+ public Benefit getBenefit(OrderMenu orderMenu, int day) {
+ Benefit benefit = new Benefit();
+ addDiscountIntoBenefitDetails(orderMenu, benefit, day);
+ return benefit;
+ }
+
+ public String getOrderMenuDetails(OrderMenu orderMenu) {
+ return orderMenu.detailsToString();
+ }
+
+ public String getTotalPriceBeforeDiscount(OrderMenu orderMenu) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), orderMenu.calculateTotalPrice());
+ }
+
+ public String getPresentationMenu(Benefit benefit) {
+ return benefit.presentationMenuToString();
+ }
+
+ public String getBenefitDetails(Benefit benefit) {
+ return benefit.detailsToString();
+ }
+
+ public String getTotalDiscount(Benefit benefit) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), benefit.calculateTotalDiscount());
+ }
+
+ public String getTotalPriceAfterDiscount(OrderMenu orderMenu, Benefit benefit) {
+ int totalPrice = orderMenu.calculateTotalPrice();
+ int totalDiscount = benefit.calculateTotalDiscount();
+ totalPrice += (totalDiscount - benefit.calculatePresentationPrice());
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), totalPrice);
+ }
+
+ public String getBadge(Benefit benefit) {
+ return Badge.findByTotalDiscount(benefit.calculateTotalDiscount());
+ }
+
+
+ private void addDiscountIntoBenefitDetails(OrderMenu orderMenu, Benefit benefit, int day) {
+ Event.findAllByDay(day)
+ .stream()
+ .filter(event -> orderMenu.calculateTotalPrice() > event.getCondition())
+ .forEach(event -> benefit.addDiscountIntoDetails(event, calculateDiscount(orderMenu, event, day)));
+ }
+
+ private int calculateDiscount(OrderMenu orderMenu, Event event, int day) {
+ int result = 0;
+ int orderMenuCount = orderMenu.countMenuByEventTarget(event.getTarget());
+ int discount = event.getDiscount();
+ int discountFromTotal = event.getDiscountFromTotal();
+ result -= (discount * orderMenuCount) + discountFromTotal;
+
+ if (event == Event.CHRISTMAS && day <= 25) {
+ result -= discount * (day - 1) + 1000;
+ }
+ if (event == Event.PRESENTATION) {
+ result -= discount;
+ }
+ return result;
+ }
+} | Java | > ์ด๋ฐ ์๋ช
ํ ์ฝ๋๋ค์ ๋ฉ์๋๋ก ๋ถ๋ฆฌํ ํ์๊ฐ ์์ด์. ์๋น์ค ๊ฐ์ฒด๊น์ง ์ด์ฉํ ํ์๋ ๋๋์ฑ ์์ด์.
์ด ๋ถ๋ถ๋ Controller์์ ๋ฐ๋ก ํธ์ถํ ์ง ๊ณ ๋ฏผํ๋ ๋ถ๋ถ์
๋๋ค. Controller์ Model(๋๋ฉ์ธ)์ ๊ด๋ จ๋ ์ฝ๋๊ฐ ์์ด๋ ๋๊ธดํ์ง๋ง Service๋ง ์์กดํ๊ฒ๋ ํ๊ณ ์ถ์๊ฑฐ๋ ์! ๊ทผ๋ฐ ๋ง์ํ์ ๋๋ก ์ด๋ฐ ์๋ช
ํ ์ฝ๋๋ค์ ๋ถํ์ํ๊ธด ํ๋ค์.. ๊ณ ๋ฏผ์ ํ๋ฒ ํด๋ด์ผ๊ฒ ์ต๋๋ค ใ
|
@@ -0,0 +1,14 @@
+package christmas.constant;
+
+public class MenuConstant {
+
+ public static class MenuType {
+
+ public static final String APPETIZER = "appetizer";
+ public static final String MAIN = "main";
+ public static final String DESSERT = "dessert";
+ public static final String DRINK = "drink";
+ public static final String NONE = "none";
+
+ }
+} | Java | > enum์ APPETIZER, MAIN, DESSERT, DRINK๋ง ์ ์ผ์
๋ ๋์ ๊ฒ ๊ฐ์์. string ์์๊ฐ ์ด์ฉ๋๋ ๊ฑธ ๋ณด์ง ๋ชปํ์ด์.
Event์๋ ์ฌ์ฉ๋๋ ์์๋ค์ด๊ธฐ ๋๋ฌธ์ ์์ํ๋ฅผ ์งํํ๊ฑฐ์์ต๋๋ค! WEEKDAY, WEEKEND์ผ๋ ๊ฐ๊ฐ dessert์ main์ ํ ์ธ ๋ฐ๊ธฐ ๋๋ฌธ์ ํด๋น string์ ์ฌ์ฌ์ฉ์ฑ์ํด ๋ฐ๋ก ์์ํ๋ฅผ ํ์ต๋๋ค! |
@@ -0,0 +1,103 @@
+package christmas.domain;
+
+import christmas.constant.EventConstant.Condition;
+import christmas.constant.EventConstant.Days;
+import christmas.constant.EventConstant.Discount;
+import christmas.constant.EventConstant.Message;
+import christmas.constant.EventConstant.Target;
+import christmas.constant.EventConstant.TotalDiscount;
+import java.util.Arrays;
+import java.util.List;
+
+public enum Event {
+
+ /*
+ index0(Condition): ์ด ์ฃผ๋ฌธ ๊ธ์ก ์กฐ๊ฑด
+ index1(Days): ์ ์ฉ ๋ ์ง
+ index2(Target): ํ ์ธ ๋ฉ๋ด ๋๋ ์ฆ์ ํ
+ index3(Discount): ํ ์ธ ๊ธ์ก
+ index4(DiscountFromTotal): ์ด๊ธ์ก์์ ํ ์ธ ๊ธ์ก
+ index5(Message): ํ ์ธ ๋ฉ์์ง (e.g. WEEKDAY -> "ํ์ผ ํ ์ธ:")
+ */
+ SPECIAL(Condition.CASE_A,
+ Days.SPECIAL,
+ Target.SPECIAL,
+ Discount.SPECIAL,
+ TotalDiscount.SPECIAL,
+ Message.SPECIAL),
+
+ WEEKDAY(Condition.CASE_A,
+ Days.WEEKDAY,
+ Target.WEEKDAY,
+ Discount.WEEKDAY,
+ TotalDiscount.OTHER,
+ Message.WEEKDAY),
+
+ WEEKEND(Condition.CASE_A,
+ Days.WEEKEND,
+ Target.WEEKEND,
+ Discount.WEEKEND,
+ TotalDiscount.OTHER,
+ Message.WEEKEND),
+
+ CHRISTMAS(Condition.CASE_A,
+ Days.EVERY,
+ Target.CHRISTMAS,
+ Discount.CHRISTMAS,
+ TotalDiscount.OTHER,
+ Message.CHRISTMAS),
+
+ PRESENTATION(Condition.CASE_B,
+ Days.EVERY,
+ Target.PRESENTATION,
+ Discount.PRESENTATION,
+ TotalDiscount.OTHER,
+ Message.PRESENTATION);
+
+
+ private final int condition;
+ private final List<Integer> days;
+ private final String target;
+ private final int discount;
+ private final int discountFromTotal;
+ private final String message;
+
+ Event(int condition, List<Integer> days, String target, int discountMenu, int discountTotal, String message) {
+ this.condition = condition;
+ this.days = days;
+ this.target = target;
+ this.discount = discountMenu;
+ this.discountFromTotal = discountTotal;
+ this.message = message;
+ }
+
+ public static List<Event> findAllByDay(int day) {
+ return Arrays.stream(Event.values())
+ .filter(event -> event.days.contains(day) || event.days.contains(day % 7))
+ .toList();
+ }
+
+ public static List<Event> getAllEvent() {
+ return Arrays.stream(Event.values()).toList();
+ }
+
+ public int getDiscount() {
+ return discount;
+ }
+
+ public int getDiscountFromTotal() {
+ return discountFromTotal;
+ }
+
+ public String getTarget() {
+ return target;
+ }
+
+ public int getCondition() {
+ return condition;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+} | Java | > ๋ด๋ถ ๊ฐ๊ณผ ๊ตฌํ์ด ๋ฟ๋ฟ์ด ํฉ์ด์ ธ ์๋ค์... ๋ณต์กํ์ง ์๋ค๋ฉด, enum ํ๋์ ์ ๋ถ ๋ฃ์ด์ฃผ์ธ์. ์ด๋ ๊ฒ ๋ง๋ค๋ฉด ์ ์ง๋ณด์๊ฐ ๋ ํ๋ค์ด์ ธ์.
์ ๋ ์์๋ค์ด ๋ง์์ ๋ณต์กํ๋ค๊ณ ์๊ฐํ์ต๋๋ค. ๊ทธ๋์ ๊ฐ๋
์ฑ๋ ๋์ผ๊ฒธ ๋ด๋ถ ๊ฐ์ ๋ฐ๋ก ๋ถ๋ฆฌํ์์ต๋๋ค! ๊ทธ๋ฆฌ๊ณ ์ ์ง๋ณด์์์๋ ํด๋น ๊ฐ๋ค์ด ๋ชจ์ฌ์๋ ํ์ผ๋ง ๋ณด๋ฉด ๋๋๋ก ์๋ํ๊ฑฐ์์ต๋๋ค! |
@@ -0,0 +1,65 @@
+package christmas.domain;
+
+import christmas.constant.MenuConstant.MenuType;
+import java.util.Arrays;
+
+public enum Menu {
+
+ //์ ํผํ์ด์
+ MUSHROOM_SOUP(MenuType.APPETIZER, "์์ก์ด์ํ", 6_000),
+ TAPAS(MenuType.APPETIZER, "ํํ์ค", 5_500),
+ CAESAR_SALAD(MenuType.APPETIZER, "์์ ์๋ฌ๋", 8_000),
+
+ //๋ฉ์ธ
+ T_BONE_STEAK(MenuType.MAIN, "ํฐ๋ณธ์คํ
์ดํฌ", 55_000),
+ BBQ_RIBS(MenuType.MAIN, "๋ฐ๋นํ๋ฆฝ", 54_000),
+ SEAFOOD_PASTA(MenuType.MAIN, "ํด์ฐ๋ฌผํ์คํ", 35_000),
+ CHRISTMAS_PASTA(MenuType.MAIN, "ํฌ๋ฆฌ์ค๋ง์คํ์คํ", 25_000),
+
+ //๋์ ํธ
+ CHOCOLATE_CAKE(MenuType.DESSERT, "์ด์ฝ์ผ์ดํฌ", 15_000),
+ ICE_CREAM(MenuType.DESSERT, "์์ด์คํฌ๋ฆผ", 5_000),
+
+ //์๋ฃ
+ ZERO_COKE(MenuType.DRINK, "์ ๋ก์ฝ๋ผ", 3_000),
+ RED_WINE(MenuType.DRINK, "๋ ๋์์ธ", 60_000),
+ CHAMPAGNE(MenuType.DRINK, "์ดํ์ธ", 25_000),
+
+ //NONE
+ NONE(MenuType.NONE, "์๋๋ฉ๋ด", 0);
+
+ private final String type;
+ private final String name;
+ private final int price;
+
+ Menu(String type, String name, int price) {
+ this.type = type;
+ this.name = name;
+ this.price = price;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public static Menu findByName(String menuName) {
+ return Arrays.stream(Menu.values())
+ .filter(menu -> menu.getName().equals(menuName))
+ .findFirst()
+ .orElse(NONE);
+ }
+
+ public static boolean isExistByName(String menuName) {
+ return Arrays.stream(Menu.values())
+ .anyMatch(menu -> menu.getName().equals(menuName));
+ }
+
+} | Java | > ์ด ์ฝ๋๋ ๊น๋ํ๊ฒ ์ ์์ฑํ์
จ๋ค์. ๐
๊ฐ์ฌํฉ๋๋ค ใ
ใ
! |
@@ -0,0 +1,30 @@
+package christmas.domain;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertAll;
+
+import java.util.List;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+class EventTest {
+
+ @DisplayName("๋ ์ง์ ํด๋นํ๋ ๋ชจ๋ ์ด๋ฒคํธ๋ค์ ์ฐพ๋๋ค.")
+ @Test
+ void findAllByDay() throws Exception {
+ //given
+ int day = 3;
+ //when
+ List<Event> events = Event.findAllByDay(3);
+ //then
+ assertAll(
+
+ () -> assertThat(events).contains(Event.WEEKDAY),
+ () -> assertThat(events).contains(Event.CHRISTMAS),
+ () -> assertThat(events).contains(Event.SPECIAL),
+ () -> assertThat(events).contains(Event.PRESENTATION)
+ );
+ }
+
+
+}
\ No newline at end of file | Java | > ํ
์คํธ ์ฝ๋๋ผ ํด๋ ๋งค์ง ๋๋ฒ๋ฅผ ์ ๊ฑฐํด์ฃผ๋ฉด ์ข์์ ๊ฒ ๊ฐ์์.
๋์ํฉ๋๋ค! ์๊ทธ๋๋ ์ ๋ฐ ๋งค์ง๋๋ฒ๋ฅผ ๋ฐ๋ก enum์ผ๋ก ์ฒ๋ฆฌํด์ ํ
์คํธํ๋ ๋ฐฉ๋ฒ์ด ์๋๋ผ๊ตฌ์ ใ
ใ
ํ๋ฒ ๊ฐ์ ํด๋ณด๊ฒ ์ต๋๋ค! |
@@ -0,0 +1,83 @@
+package christmas.service;
+
+import christmas.constant.Constant;
+import christmas.domain.Badge;
+import christmas.domain.Benefit;
+import christmas.domain.Event;
+import christmas.domain.OrderMenu;
+import christmas.view.input.template.InputCallback;
+import christmas.view.input.template.InputTemplate;
+
+public class ChristmasService {
+
+ private final InputTemplate inputTemplate;
+
+ public ChristmasService() {
+ this.inputTemplate = new InputTemplate();
+ }
+
+ public <T> T getInputRequestResult(InputCallback<T> callback) {
+ return inputTemplate.execute(callback);
+ }
+
+ public Benefit getBenefit(OrderMenu orderMenu, int day) {
+ Benefit benefit = new Benefit();
+ addDiscountIntoBenefitDetails(orderMenu, benefit, day);
+ return benefit;
+ }
+
+ public String getOrderMenuDetails(OrderMenu orderMenu) {
+ return orderMenu.detailsToString();
+ }
+
+ public String getTotalPriceBeforeDiscount(OrderMenu orderMenu) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), orderMenu.calculateTotalPrice());
+ }
+
+ public String getPresentationMenu(Benefit benefit) {
+ return benefit.presentationMenuToString();
+ }
+
+ public String getBenefitDetails(Benefit benefit) {
+ return benefit.detailsToString();
+ }
+
+ public String getTotalDiscount(Benefit benefit) {
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), benefit.calculateTotalDiscount());
+ }
+
+ public String getTotalPriceAfterDiscount(OrderMenu orderMenu, Benefit benefit) {
+ int totalPrice = orderMenu.calculateTotalPrice();
+ int totalDiscount = benefit.calculateTotalDiscount();
+ totalPrice += (totalDiscount - benefit.calculatePresentationPrice());
+ return String.format(Constant.PRICE_UNIT + System.lineSeparator(), totalPrice);
+ }
+
+ public String getBadge(Benefit benefit) {
+ return Badge.findByTotalDiscount(benefit.calculateTotalDiscount());
+ }
+
+
+ private void addDiscountIntoBenefitDetails(OrderMenu orderMenu, Benefit benefit, int day) {
+ Event.findAllByDay(day)
+ .stream()
+ .filter(event -> orderMenu.calculateTotalPrice() > event.getCondition())
+ .forEach(event -> benefit.addDiscountIntoDetails(event, calculateDiscount(orderMenu, event, day)));
+ }
+
+ private int calculateDiscount(OrderMenu orderMenu, Event event, int day) {
+ int result = 0;
+ int orderMenuCount = orderMenu.countMenuByEventTarget(event.getTarget());
+ int discount = event.getDiscount();
+ int discountFromTotal = event.getDiscountFromTotal();
+ result -= (discount * orderMenuCount) + discountFromTotal;
+
+ if (event == Event.CHRISTMAS && day <= 25) {
+ result -= discount * (day - 1) + 1000;
+ }
+ if (event == Event.PRESENTATION) {
+ result -= discount;
+ }
+ return result;
+ }
+} | Java | ์ธ๋ถ์์ benefit์ ๋ฐ์์ค์ง ๋ง๊ณ , ๋ด๋ถ์์ ์์ฑํ๊ณ ๋ฐํํ๋ ๊ฒ ์ข๋ค๋ ๋ป์ด์์ด์.
```suggestion
private Benefit addDiscountIntoBenefitDetails(OrderMenu orderMenu, int day) {
Benefit benefit = new Benefit();
Event.findAllByDay(day)
.stream()
.filter(event -> orderMenu.calculateTotalPrice() > event.getCondition())
.forEach(event -> benefit.addDiscountIntoDetails(event, calculateDiscount(orderMenu, event, day)));
return benefit;
}
```
๋น๋๋ฅผ ๋ง๋ค๋ฉด, ํด๋น ์์
์ ๋น๋๊ฐ ๋์ ํ๊ฒ ๋ ๊ฑฐ์์! |
@@ -0,0 +1,164 @@
+# ๐ํฌ๋ฆฌ์ค๋ง์ค ํ๋ก๋ชจ์
App๐
+
+๋ณธ ์ดํ๋ฆฌ์ผ์ด์
์ ์ฐํ
์ฝ ์๋น์์ ์ฃผ๋ฌธ ๋ฉ๋ด์ ๋ฐ๋ผ ๋ฐ๊ฒ ๋๋ 2023๋
12์ ํํ๋ค์ ๋ฏธ๋ฆฌ๋ณผ ์ ์๋ ๊ธฐ๋ฅ์ ์ ๊ณตํฉ๋๋ค.
+
+## ๐ ์งํ๊ณผ์
+
+1. ๋ฐฉ๋ฌธ์ ํฌ๋งํ์๋ ๋ ์ง๋ฅผ ์
๋ ฅํด์ฃผ์ธ์
+
+- ๋ ์ง๋ ์ซ์๋ง ์
๋ ฅํด์ฃผ์ธ์ (๊ณต๋ฐฑ์ ํฌํจ ๋์ด๋ ๊ด์ฐฎ์ต๋๋ค.)
+
+```
+์๋
ํ์ธ์! ์ฐํ
์ฝ ์๋น 12์ ์ด๋ฒคํธ ํ๋๋์
๋๋ค.
+12์ ์ค ์๋น ์์ ๋ฐฉ๋ฌธ ๋ ์ง๋ ์ธ์ ์ธ๊ฐ์? (์ซ์๋ง ์
๋ ฅํด ์ฃผ์ธ์!)
+3
+```
+
+2. ์ฃผ๋ฌธํ ๋ฉ๋ด๋ฅผ ๊ฐฏ์์ ํจ๊ป ์
๋ ฅํด์ฃผ์ธ์
+
+- `๋ฉ๋ด์ด๋ฆ-๋ฉ๋ด๊ฐฏ์` ํ์์ ๊ผญ ์ง์ผ์ฃผ์ธ์ (๊ณต๋ฐฑ์ ํฌํจ ๋์ด๋ ๊ด์ฐฎ์ต๋๋ค.)
+- ๋ฉ๋ด๋ ๊ผญ 1๊ฐ ์ด์ ์ฃผ๋ฌธํด์ฃผ์ธ์(e.g. ํด์ฐ๋ฌผํ์คํ-1 [O] // ํด์ฐ๋ฌผํ์คํ-0 [X])
+- ๊ฐ ๋ฉ๋ด์ ๊ฐฏ์ ํฉ์ 20๊ฐ ์ดํ๋ก ์ฃผ๋ฌธํด์ฃผ์ธ์(e.g. ๋ฐ๋นํ๋ฆฝ-5,๋ ๋์์ธ-5 [O] // ๋ฐ๋นํ๋ฆฝ-11, ๋ ๋์์ธ-10 [X])
+- ์๋ฃ๋ง ์ฃผ๋ฌธํ ์ ์์ด์.
+- ๋ฉ๋ดํ์ ์๋ ๋ฉ๋ด๋ ์ฃผ๋ฌธํ ์ ์์ด์
+- ์ค๋ณต๋ ๋ฉ๋ด๋ ์ฃผ๋ฌธํ ์ ์์ด์(e.g. ํด์ฐ๋ฌผํ์คํ-2,ํด์ฐ๋ฌผํ์คํ-1 [X])
+
+```
+ํฐ๋ณธ์คํ
์ดํฌ-1,๋ฐ๋นํ๋ฆฝ-1,์ด์ฝ์ผ์ดํฌ-2,์ ๋ก์ฝ๋ผ-1
+```
+
+3. ์ฃผ๋ฌธ ๋ฐ ํํ์ ํ์ธํด์ฃผ์ธ์
+
+- ์ฃผ๋ฌธ ๋ฉ๋ด ๋ถํฐ ์์ํด์ ์ด 7๊ฐ์ง์ ํ์ดํ์ ํด๋นํ๋ ๋ด์ญ๋ค์ด ๋ง๋์ง ํ์ธํด์ฃผ์ธ์.
+- ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก์ **์ฆ์ ์ด๋ฒคํธ ํ ์ธ์ ์ ์ธ**ํ ๊ธ์ก์ด์์
+
+```
+<์ฃผ๋ฌธ ๋ฉ๋ด>
+ํฐ๋ณธ์คํ
์ดํฌ 1๊ฐ
+๋ฐ๋นํ๋ฆฝ 1๊ฐ
+์ด์ฝ์ผ์ดํฌ 2๊ฐ
+์ ๋ก์ฝ๋ผ 1๊ฐ
+
+<ํ ์ธ ์ ์ด์ฃผ๋ฌธ ๊ธ์ก>
+142,000์
+
+<์ฆ์ ๋ฉ๋ด>
+์ดํ์ธ 1๊ฐ
+
+<ํํ ๋ด์ญ>
+ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ: -1,200์
+ํ์ผ ํ ์ธ: -4,046์
+ํน๋ณ ํ ์ธ: -1,000์
+์ฆ์ ์ด๋ฒคํธ: -25,000์
+
+<์ดํํ ๊ธ์ก>
+-31,246์
+
+<ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก>
+135,754์
+
+<12์ ์ด๋ฒคํธ ๋ฐฐ์ง>
+์ฐํ
+```
+
+## ๐ฏ ๊ธฐ๋ฅ ๊ตฌํ ๋ชฉ๋ก
+
+- ### ๋ฉ๋ดํ(Menu)
+ - [X] ํ๋งค ์ค์ธ ๋ฉ๋ด๋ค์ ์ด๊ฑฐํ์ฌ ์ ์ฅํ ์ ์๋ ๊ณณ ์
๋๋ค.
+ - [X] ๊ฐ ๋ฉ๋ด๋ ํ์
๊ณผ ๊ฐ๊ฒฉ ์ ๋ณด๋ฅผ ๊ฐ๊ณ ์์ต๋๋ค.
+ - [X] ๋ฉ๋ดํ์ ๋ฉ๋ด์ ์กด์ฌ์ฌ๋ถ๋ฅผ ํ์ธํฉ๋๋ค.
+- ### ์ฃผ๋ฌธ(OrderMenu)
+ - [X] ์ฌ์ฉ์ ์
๋ ฅํ ์ฃผ๋ฌธ ๋ด์ญ๋ค์ ์ ์ฅํฉ๋๋ค.
+ - [X] ์์ธ์ฒ๋ฆฌ
+ - ๋ฉ๋ดํ์ ์๋ ๋ฉ๋ด๋ฅผ ์
๋ ฅํ ๊ฒฝ์ฐ
+ - ์ค๋ณต ๋ฉ๋ด๋ฅผ ์
๋ ฅํ ๊ฒฝ์ฐ
+ - ์๋ฃ ๋ฉ๋ด๋ง ์
๋ ฅํ ๊ฒฝ์ฐ
+ - ๋ฉ๋ด ๊ฐฏ์์ ํฉ์ด 20์ ์ด๊ณผํ ๊ฒฝ์ฐ
+ - [X] ์ฌ์ฉ์์๊ฒ ๋ณด์ฌ์ค ์ฃผ๋ฌธ ๋ด์ญ์ ๋ง๋ญ๋๋ค.
+ - [X] ์ฃผ๋ฌธํ ์ด๊ธ์ก์ ๊ณ์ฐํฉ๋๋ค.
+ - [X] ์ด๋ฒคํธ ๋์์ธ ๋ฉ๋ด์ ๊ฐฏ์๋ฅผ ๊ณ์ฐํฉ๋๋ค.
+- ### ์ด๋ฒคํธ(Event)
+ - [X] ์งํ ์ค์ธ ์ด๋ฒคํธ๋ค์ ์ด๊ฑฐํ์ฌ ์ ์ฅํ ์ ์๋ ๊ณณ ์
๋๋ค.
+ - [X] ๊ฐ ์ด๋ฒคํธ๋ ํด๋นํ๋ ์ ๋ณด๋ค์ ๊ฐ๊ณ ์์ต๋๋ค.
+ - ์กฐ๊ฑด(์ฃผ๋ฌธ ์ด ๊ธ์ก์ผ๋ก ๊ฒฐ์ ๋จ)
+ - ์ ์ฉ ๋ ์ง
+ - ๋์ ๋ฉ๋ด ๋๋ ์ฆ์ ํ
+ - ํ ์ธ ๊ธ์ก
+ - ์ฃผ๋ฌธ ์ด ๊ธ์ก์์ ํ ์ธ ๊ธ์ก
+ - ํ ์ธ ์ ๋ฉ์ธ์ง
+ - [X] ์
๋ ฅ๋ ๋ ์ง์ ํด๋นํ๋ ๋ชจ๋ ์ด๋ฒคํธ๋ค์ ์ฐพ์ต๋๋ค.
+ - [X] ์ ์ฅ๋์ด ์๋ ๋ชจ๋ ์ด๋ฒคํธ๋ค์ ๋ฐํํฉ๋๋ค.
+- ### ํํ(Benefit)
+ - [X] ํํ ๋ฐ์ ๋ด์ญ๋ค์ ์ ์ฅํ๋ ๊ณณ ์
๋๋ค.
+ - [X] ํ ์ธ ๋ฐ์ ์ด ๊ธ์ก์ ๊ณ์ฐํฉ๋๋ค.
+ - [X] ์ด๋ฒคํธ ๋ณ ํ ์ธ ๋ฐ์ ๊ธ์ก์ ์ถ๊ฐํฉ๋๋ค.
+ - [X] ์ฌ์ฉ์์๊ฒ ๋ณด์ฌ์ค ํํ ๋ด์ญ์ ๋ง๋ญ๋๋ค.
+ - [X] ์ฆ์ ์ด๋ฒคํธ ํ ์ธ ๊ฐ๊ฒฉ์ ๊ณ์ฐํฉ๋๋ค.
+ - [X] ์ฌ์ฉ์์๊ฒ ๋ณด์ฌ์ค ์ฆ์ ๋ฉ๋ด ๋ด์ญ์ ๋ง๋ญ๋๋ค.
+- ### ๋ฐฐ์ง(Badge)
+ - [X] ์ด๋ฒคํธ ๋ฐฐ์ง๋ค์ ์ด๊ฑฐํ์ฌ ์ ์ฅํ ์ ์๋ ๊ณณ ์
๋๋ค.
+ - [X] ์ด ํ ์ธ ๊ธ์ก์ผ๋ก ํด๋นํ๋ ๋ฐฐ์ง๋ฅผ ์ฐพ์ต๋๋ค.
+- ### ํฌ๋ฆฌ์ค๋ง์ค ์๋น์ค(ChristMasService)
+ - [X] ์ฃผ๋ฌธ ๋ฉ๋ด์ ๋ ์ง์ ๋ง๊ฒ ํํ ๋ด์ญ์ ์์ฑํฉ๋๋ค.
+ - [X] ์ฆ์ ๋ฉ๋ด ๊ฐ๊ฒฉ์ ๊ฐ์ ธ์ต๋๋ค.(ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก์ ๊ณ์ฐ์ ์ํด ์ฌ์ฉ)
+ - [X] ์ฌ์ฉ์์๊ฒ ๋ณด์ฌ์ค ํญ๋ชฉ๋ค์ ๊ฐ์ ธ์ต๋๋ค.
+ - ์ฃผ๋ฌธ ๋ฉ๋ด ๋ด์ญ
+ - ํ ์ธ ์ ์ด์ฃผ๋ฌธ ๊ธ์ก
+ - ์ฆ์ ๋ฉ๋ด
+ - ํํ ๋ด์ญ
+ - ์ดํํ ๊ธ์ก
+ - ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก
+ - 12์ ์ด๋ฒคํธ ๋ฐฐ์ง
+- ### View(InputView / OutputView)
+ - #### InputView
+ - [X] ์ฌ์ฉ์์๊ฒ ๋ฉ๋ด์ ๋ ์ง๋ฅผ ๋ฐ์ต๋๋ค.
+ - [X] ์์ธ์ฒ๋ฆฌ
+ - `๋ฉ๋ด์ด๋ฆ-๋ฉ๋ด๊ฐฏ์` ํ์์ด ์๋๊ฒฝ์ฐ
+ - ๊ฐ ๋ฉ๋ด์ ๊ฐฏ์๊ฐ 1์ด์์ด ์๋ ๊ฒฝ์ฐ
+ - ๋ ์ง๊ฐ ์ซ์๊ฐ ์๋ ๊ฒฝ์ฐ
+ - ๋ ์ง๊ฐ 1๊ณผ31 ์ฌ์ด๊ฐ ์๋ ๊ฒฝ์ฐ
+ - #### OutputView
+ -[X] ์๊ตฌ์ฌํญ์ ๋ง๊ฒ ๋ด์ญ๋ค์ ์ถ๋ ฅํฉ๋๋ค.
+ - ์ด๋์
๋ฉํธ
+ - ๋ ์ง ์์ฒญ ๋ฉ์์ง / ์ฃผ๋ฌธ ๋ฉ๋ด ์์ฒญ ๋ฉ์์ง
+ - ์ฃผ๋ฌธ ๋ฉ๋ด ๋ด์ญ
+ - ํ ์ธ ์ ์ด์ฃผ๋ฌธ ๊ธ์ก
+ - ์ฆ์ ๋ฉ๋ด
+ - ํํ ๋ด์ญ
+ - ์ดํํ ๊ธ์ก
+ - ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก
+ - 12์ ์ด๋ฒคํธ ๋ฐฐ์ง
+
+## ๐ฆ ํจํค์ง ๊ตฌ์กฐ
+
+
+
+## ๐บ๏ธ ํ๋ก์ฐ ์ฐจํธ
+
+```mermaid
+flowchart TD
+ A([Application<br>App ์คํ]) --> B[/OutputView<br>๋ ์ง ์
๋ ฅ ์์ฒญ ๋ฉ์ธ์ง ์ถ๋ ฅ/] --> C[/InputView<br>๋ ์ง ์
๋ ฅ/]
+ C --> D{Validator<br>๋ ์ง ์ ํจ์ฑ ๊ฒ์ฆ} -->|NO| C
+ D -->|YES| E[/OutputView<br>์ฃผ๋ฌธ ๋ฉ๋ด ์
๋ ฅ ์์ฒญ ๋ฉ์์ง ์ถ๋ ฅ/] --> F[/InputputView<br>์ฃผ๋ฌธ ๋ฉ๋ด ์
๋ ฅ/]
+ F --> G{Validator<br>์ฃผ๋ฌธ ๋ฉ๋ด ์ ํจ์ฑ ๊ฒ์ฆ} -->|NO| F
+ G -->|YES| H[ChristmasService<br>๊ฐ ๋๋ฉ์ธ์ผ๋ก ๋ถํฐ ํ์ํ ๋ด์ญ๋ค์ ์์ฐจ์ ์ผ๋ก ๊ฐ์ ธ์ด]
+ H --> I[/OutputView<br>ํํ ๋ด์ญ๋ค ์์ฐจ์ ์ผ๋ก ์ถ๋ ฅ/] --> J([Application<br>App ์ข
๋ฃ])
+```
+
+## ๐งฉ ํด๋์ค ๋ค์ด์ด๊ทธ๋จ
+
+- ### domain
+
+
+
+---
+
+- ### controller
+
+
+
+---
+
+- ### constant
+
+
\ No newline at end of file | Unknown | ๋ฌธ์ ๊ผผ๊ผผํ๊ฒ ์ฝ์ด๋ดค์ต๋๋ค! ํ์คํ ์ด๋ฏธ์ง๋ก ๋ฐ์ดํฐ ์ฒ๋ฆฌ์ ์์๋๋ฅผ ํ์ธํ๋๊น ๊ฐ์์ฑ์ด ์ข๋ค์:) |
@@ -0,0 +1,16 @@
+package christmas.constant;
+
+import java.util.regex.Pattern;
+
+public class Constant {
+
+ public static final String DELIMITER_COMMA = ",";
+ public static final String DELIMITER_HYPHEN = "-";
+ public static final String SPACE = " ";
+ public static final String MENU_UNIT = "%d๊ฐ";
+ public static final String PRICE_UNIT = "%,d์";
+ public static final String NOTHING = "์์";
+ public static final int MENU_MAXIMUM_QUANTITY = 20;
+ public static final Pattern MENU_PATTERN = Pattern.compile("^[a-z|A-z|ใฑ-ใ
|๊ฐ-ํฃ|0-9|\s]+-[0-9\s]+$");
+ public static final Pattern DAY_PATTERN = Pattern.compile("^[0-9\s]+$");
+} | Java | ์ ๊ท ํํ์๊น์ง ํ์ฉํด์ ์์ ๊ด๋ฆฌํ๋ ๋ถ๋ถ์์ ์ต๋ํ ๋จ์ผ ํด๋์ค ํ์ private ํ๋ ์์๋ฅผ ์ค์ด๋ ค๊ณ ํ์ ๋
ธ๋ ฅ์ด ๋ณด์
๋๋ค. ์์ฃผ ์ข๋ค์! |
@@ -0,0 +1,58 @@
+package christmas.constant;
+
+import christmas.constant.MenuConstant.MenuType;
+import christmas.domain.Menu;
+import java.util.List;
+
+public class EventConstant {
+ public static class Condition {
+
+ public static final int CASE_A = 10000;
+ public static final int CASE_B = 120000;
+ }
+
+ public static class Days {
+
+ public static final List<Integer> EVERY = List.of(1, 2, 3, 4, 5, 6);
+ public static final List<Integer> WEEKDAY = List.of(0, 3, 4, 5, 6);
+ public static final List<Integer> WEEKEND = List.of(1, 2);
+ public static final List<Integer> SPECIAL = List.of(3, 25);
+
+ }
+
+ public static class Target {
+
+ public static final String WEEKDAY = MenuType.DESSERT;
+ public static final String WEEKEND = MenuType.MAIN;
+ public static final String CHRISTMAS = MenuType.NONE;
+ public static final String SPECIAL = MenuType.NONE;
+ public static final String PRESENTATION = Menu.CHAMPAGNE.getName();
+
+ }
+
+ public static class Discount {
+
+ public static final int WEEKDAY = 2023;
+ public static final int WEEKEND = 2023;
+ public static final int CHRISTMAS = 100;
+ public static final int SPECIAL = 0;
+ public static final int PRESENTATION = Menu.CHAMPAGNE.getPrice() * 1;
+
+ }
+
+ public static class TotalDiscount {
+ public static final int SPECIAL = 1000;
+ public static final int OTHER = 0;
+ }
+
+ public static class Message {
+
+ public static final String SPECIAL = "ํน๋ณ ํ ์ธ:";
+ public static final String WEEKDAY = "ํ์ผ ํ ์ธ:";
+ public static final String WEEKEND = "์ฃผ๋ง ํ ์ธ:";
+ public static final String CHRISTMAS = "ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ:";
+ public static final String PRESENTATION = "์ฆ์ ์ด๋ฒคํธ:";
+
+ }
+
+} | Java | ๋ฐฑ์ ์๋ฆฌ๋ฅผ ๊ธฐ์ค์ผ๋ก ๊ตฌ๋ถ์ "_"๋ฅผ ๋ฃ์ด์ฃผ์๋ฉด ๊ฐ๋
์ฑ์ด ์ฆ์ง๋ ๊ฒ ๊ฐ์ต๋๋ค:) |
@@ -0,0 +1,58 @@
+package christmas.constant;
+
+import christmas.constant.MenuConstant.MenuType;
+import christmas.domain.Menu;
+import java.util.List;
+
+public class EventConstant {
+ public static class Condition {
+
+ public static final int CASE_A = 10000;
+ public static final int CASE_B = 120000;
+ }
+
+ public static class Days {
+
+ public static final List<Integer> EVERY = List.of(1, 2, 3, 4, 5, 6);
+ public static final List<Integer> WEEKDAY = List.of(0, 3, 4, 5, 6);
+ public static final List<Integer> WEEKEND = List.of(1, 2);
+ public static final List<Integer> SPECIAL = List.of(3, 25);
+
+ }
+
+ public static class Target {
+
+ public static final String WEEKDAY = MenuType.DESSERT;
+ public static final String WEEKEND = MenuType.MAIN;
+ public static final String CHRISTMAS = MenuType.NONE;
+ public static final String SPECIAL = MenuType.NONE;
+ public static final String PRESENTATION = Menu.CHAMPAGNE.getName();
+
+ }
+
+ public static class Discount {
+
+ public static final int WEEKDAY = 2023;
+ public static final int WEEKEND = 2023;
+ public static final int CHRISTMAS = 100;
+ public static final int SPECIAL = 0;
+ public static final int PRESENTATION = Menu.CHAMPAGNE.getPrice() * 1;
+
+ }
+
+ public static class TotalDiscount {
+ public static final int SPECIAL = 1000;
+ public static final int OTHER = 0;
+ }
+
+ public static class Message {
+
+ public static final String SPECIAL = "ํน๋ณ ํ ์ธ:";
+ public static final String WEEKDAY = "ํ์ผ ํ ์ธ:";
+ public static final String WEEKEND = "์ฃผ๋ง ํ ์ธ:";
+ public static final String CHRISTMAS = "ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ:";
+ public static final String PRESENTATION = "์ฆ์ ์ด๋ฒคํธ:";
+
+ }
+
+} | Java | ์ ์ ์ค์ฒฉ ํด๋์ค๋ฅผ ํ์ฉํด์ ์ธ์คํด์คํ๋ฅผ ๋ฐฉ์งํ ์ ์๋ค์...! ์ถ๊ฐ๋ก ๊ฐ ํด๋์ค ๋ณ๋ก ๊ณต๋ฐฑ ์ค๋ฐ๊ฟ์ ํ์ฉํด์ ๊ฐ๋
์ฑ์ ๋์ด์ ๊ฒ ์์ฃผ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค:) |
@@ -0,0 +1,87 @@
+package christmas.controller;
+
+import christmas.domain.Benefit;
+import christmas.domain.OrderMenu;
+import christmas.service.ChristmasService;
+import christmas.view.input.InputView;
+import christmas.view.output.OutputView;
+
+public class ChristmasController {
+
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final ChristmasService christmasService;
+
+ public ChristmasController() {
+ this.inputView = new InputView();
+ this.outputView = new OutputView();
+ this.christmasService = new ChristmasService();
+ }
+
+ public void run() {
+ int day = requestDay();
+ OrderMenu orderMenu = requestOrderMenu();
+ Benefit benefit = christmasService.getBenefit(orderMenu, day);
+ responseAll(orderMenu, benefit);
+
+ }
+
+ private int requestDay() {
+ outputView.printRequestDayMessage();
+ return christmasService.getInputRequestResult(inputView::requestDay);
+ }
+
+ private OrderMenu requestOrderMenu() {
+ outputView.printRequestOrderMessage();
+ return christmasService.getInputRequestResult(inputView::requestOrderMenu);
+ }
+
+ private void responseAll(OrderMenu orderMenu, Benefit benefit) {
+ outputView.printPreviewMessage();
+
+ responseOrderMenusDetails(orderMenu);
+ responseTotalPriceBeforeDiscount(orderMenu);
+ responsePresentationMenu(benefit);
+ responseBenefitDetails(benefit);
+ responseTotalDiscount(benefit);
+ responseTotalPriceAfterDiscount(orderMenu, benefit);
+ responseBadge(benefit);
+ }
+
+ private void responseOrderMenusDetails(OrderMenu orderMenus) {
+ String orderMenusDetails = christmasService.getOrderMenuDetails(orderMenus);
+ outputView.printOrderMenusDetails(orderMenusDetails);
+ }
+
+ private void responseTotalPriceBeforeDiscount(OrderMenu orderMenu) {
+ String totalPriceBeforeDiscount = christmasService.getTotalPriceBeforeDiscount(orderMenu);
+ outputView.printTotalPriceBeforeDiscount(totalPriceBeforeDiscount);
+ }
+
+ private void responsePresentationMenu(Benefit benefit) {
+ String presentationMenu = christmasService.getPresentationMenu(benefit);
+ outputView.printPresentationMenu(presentationMenu);
+ }
+
+ private void responseBenefitDetails(Benefit benefit) {
+ String benefitDetails = christmasService.getBenefitDetails(benefit);
+ outputView.printBenefitDetails(benefitDetails);
+ }
+
+ private void responseTotalDiscount(Benefit benefit) {
+ String totalDiscount = christmasService.getTotalDiscount(benefit);
+ outputView.printTotalDiscount(totalDiscount);
+ }
+
+ private void responseTotalPriceAfterDiscount(OrderMenu orderMenus, Benefit benefit) {
+ String totalPriceAfterDiscount = christmasService.getTotalPriceAfterDiscount(orderMenus, benefit);
+ outputView.printTotalPriceAfterDiscount(totalPriceAfterDiscount);
+ }
+
+ private void responseBadge(Benefit benefit) {
+ String badge = christmasService.getBadge(benefit);
+ outputView.printBadge(badge);
+ }
+
+
+} | Java | ์์ฒญ๊ฐ๋ค์ ์ ๋ถ ๋ฐ์์ ์ํ๋ ๋ฆฌํด๊ฐ์ ๋ด๋๋ ๋ฉ์๋ ๊ฐ์๋ฐ ๋ช
๋ช
์ด ์กฐ๊ธ ์์ฌ์ด ๊ฒ ๊ฐ์ต๋๋ค! ๋ ์ข์ ๋ฉ์๋ ๋ช
๋ช
์ด ์์ง ์์์๊น ์ถ์ด์:) |
@@ -0,0 +1,72 @@
+package christmas.domain;
+
+import christmas.constant.Constant;
+import java.util.EnumMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+public class Benefit {
+
+ private final Map<Event, Integer> details;
+
+ public Benefit() {
+ this.details = new EnumMap<>(Event.class);
+ initialBenefitDetails();
+ }
+
+ public int calculateTotalDiscount() {
+ return details.values()
+ .stream()
+ .reduce(0, Integer::sum);
+ }
+
+ public void addDiscountIntoDetails(Event event, int discount) {
+ details.computeIfPresent(event, (key, value) -> value + discount);
+ }
+
+ public String detailsToString() {
+ StringBuilder sb = new StringBuilder(Constant.NOTHING + System.lineSeparator());
+ if (calculateTotalDiscount() != 0) {
+ sb.setLength(0);
+ appendDetails(sb);
+ }
+ return sb.toString();
+ }
+
+ public int calculatePresentationPrice() {
+ return details.get(Event.PRESENTATION);
+ }
+
+ public String presentationMenuToString() {
+ Event presentation = Event.PRESENTATION;
+ StringBuilder sb = new StringBuilder(Constant.NOTHING + System.lineSeparator());
+ int discount = details.get(presentation);
+ if (discount != 0) {
+ sb.setLength(0);
+ sb.append(presentation.getTarget());
+ sb.append(Constant.SPACE);
+ sb.append(String.format(Constant.MENU_UNIT, Math.abs(discount / Event.PRESENTATION.getDiscount())));
+ sb.append(System.lineSeparator());
+ }
+ return sb.toString();
+ }
+
+
+ private void appendDetails(StringBuilder benefitDetail) {
+ for (Entry<Event, Integer> entry : details.entrySet()) {
+ String eventMessage = entry.getKey().getMessage();
+ int discount = entry.getValue();
+ if (discount != 0) {
+ benefitDetail.append(eventMessage);
+ benefitDetail.append(Constant.SPACE);
+ benefitDetail.append(String.format(Constant.PRICE_UNIT, discount));
+ benefitDetail.append(System.lineSeparator());
+ }
+ }
+ }
+
+ private void initialBenefitDetails() {
+ Event.getAllEvent().forEach(event -> details.put(event, 0));
+ }
+
+} | Java | ์ดํํ๊ฐ์ด 0์ธ์ง ์๋์ง๋ฅผ ๋ถ๊ธฐ์ ์ผ๋ก ๋ฌ์ ์ถ๋ ฅ ์ฌ๋ถ๋ฅผ ๊ฒฐ์ ์ผ ํ๋ค์! ์๋ฌ๋ ๋ก์ง์ ๋ณด๋๊น ๊ตณ์ด ๊ฐ์ ๋ฐ๋ก๋ฐ๋ก ์๊ฐํ ํ์๊ฐ ์์์ ๊ฒ ๊ฐ๋ค์. ์ข์ ์์ด๋์ด ๊ฐ์ต๋๋ค:) |
@@ -0,0 +1,82 @@
+package study;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+public class Equation {
+
+ private final String equation;
+
+ private static final String INVALID_CALCULATION_FORMAT = "์๋ชป๋ ๊ณ์ฐ์์
๋๋ค.";
+ private static final String DELIMITER = " ";
+
+ public Equation(String equation) {
+ this.equation = equation;
+ checkEquation();
+ }
+
+ public void checkEquation() {
+ String[] split = equation.split(DELIMITER);
+
+ for (int i = 0; i < split.length; ) {
+ checkDoubleNumber(split, i);
+ i += 2;
+ }
+
+ for (int i = 1; i < split.length; ) {
+ checkDoubleSymbol(split, i);
+ i += 2;
+ }
+
+ }
+
+ public List<Integer> getNumbers() {
+ List<Integer> numList = new ArrayList<>();
+ String[] inputArr = equation.split(DELIMITER);
+ Arrays.stream(inputArr).filter(this::isParesInt).forEach(s -> addNumList(numList, s));
+ return numList;
+ }
+
+ public List<String> getSymbolsList() {
+ List<String> symbolList = new ArrayList<>();
+ String[] inputArr = equation.split(DELIMITER);
+ Arrays.stream(inputArr).filter(s -> !isParesInt(s))
+ .forEach(s -> addSymbolList(symbolList, s));
+ return symbolList;
+ }
+
+ private boolean isParesInt(String input) {
+ return input.chars().allMatch(Character::isDigit);
+ }
+
+ private void addNumList(List<Integer> numList, String input) {
+ numList.add(Integer.parseInt(input));
+ }
+
+ private void addSymbolList(List<String> symbolList, String input) {
+ checkSymbol(input);
+ symbolList.add(input);
+ }
+
+ private void checkSymbol(String input) {
+ if (!SymbolStatus.checkSymbol(input)) {
+ throw new IllegalStateException(INVALID_CALCULATION_FORMAT);
+ }
+ }
+
+ private void checkDoubleNumber(String[] split, int i) {
+ boolean parseInt = isParesInt(split[i]);
+ if (!parseInt) {
+ throw new IllegalStateException(INVALID_CALCULATION_FORMAT);
+ }
+ }
+
+ private void checkDoubleSymbol(String[] split, int i) {
+ boolean parse = isParesInt(split[i]);
+ if (parse) {
+ throw new IllegalStateException(INVALID_CALCULATION_FORMAT);
+ }
+ }
+
+} | Java | ํด๋์ค์ ๊ตฌํ ์ปจ๋ฒค์
์ ๋ง์ถฐ์ ๊ตฌํํ๊ฒ๋๋ฉด ์ผ๊ด๋ ์ฝ๋๋ฅผ ์์ฑํ ์ ์์ต๋๋ค :)
```
class A {
์์(static final) ๋๋ ํด๋์ค ๋ณ์
์ธ์คํด์ค ๋ณ์
์์ฑ์
ํฉํ ๋ฆฌ ๋ฉ์๋
๋ฉ์๋
๊ธฐ๋ณธ ๋ฉ์๋ (equals, hashCode, toString)
}
``` |
@@ -0,0 +1,16 @@
+package study;
+
+import java.util.Scanner;
+
+public class InputView {
+
+ private Scanner scanner;
+
+ public InputView(Scanner scanner) {
+ this.scanner = scanner;
+ }
+
+ public String readEquation() {
+ return scanner.nextLine();
+ }
+} | Java | InputView์์ ์์ฑ์์ ํ๋ผ๋ฏธํฐ๋ก Scanner๋ฅผ ์ค์ ํด์ฃผ์ ์ด์ ๊ฐ ์์๊น์?
์์ฑ์๋ฅผ ํตํ ์์กด์ฑ ์ฃผ์
์ ํตํด ์ป๊ฒ๋๋ ์ฅ์ ์ด ์์ด๋ณด์ด๋ ๊ฒ ๊ฐ์์ ๐ค |
@@ -0,0 +1,13 @@
+package study;
+
+public class ResultView {
+
+ public void initStart() {
+ System.out.println("๊ณ์ฐ์์ ์
๋ ฅํ์ธ์.");
+ }
+
+ public void viewResult(SimpleCalculator simpleCalculator) {
+ int result = simpleCalculator.calEquation();
+ System.out.println("๊ณ์ฐ ๊ฒฐ๊ณผ = " + result);
+ }
+} | Java | ๊ณ์ฐ์์ ์
๋ ฅํ๋ผ๊ณ ์ฝ์์ ์ถ๋ ฅ๋๋ ๋ด์ฉ์ InputView์ ์ข ๋ ์ ํฉํด๋ณด์ด๊ธฐ๋ ํ๋ค์.
InputView์ ResultView๋ฅผ ๊ตฌ๋ถํ๋ ์ด์ ๋ ์์ฒญ๊ณผ ๊ฒฐ๊ณผ๋ฅผ ๊ตฌ๋ถํ๊ธฐ ์ํ ๋ถ๋ถ์ด๊ธฐ ๋๋ฌธ์ ResultView์์๋ง ์ถ๋ ฅ์ ํด์ผํ๋ ๊ฒ์ ์๋๋๋ค :) |
@@ -0,0 +1,13 @@
+package study;
+
+public class ResultView {
+
+ public void initStart() {
+ System.out.println("๊ณ์ฐ์์ ์
๋ ฅํ์ธ์.");
+ }
+
+ public void viewResult(SimpleCalculator simpleCalculator) {
+ int result = simpleCalculator.calEquation();
+ System.out.println("๊ณ์ฐ ๊ฒฐ๊ณผ = " + result);
+ }
+} | Java | ๊ณ์ฐ๊ธฐ ๊ฐ์ฒด๋ฅผ viewResult()์ ์ธ์๋ก ๋๊ธฐ๋ ๊ฒ ๋ณด๋ค๋ ๊ฒฐ๊ณผ ๊ฐ์ ๋๊ฒจ์ฃผ๋ ๊ฒ์ ์ด๋จ๊น์?
๊ณ์ฐ๊ธฐ ๊ฐ์ฒด์ View ๊ฐ์ฒด๋ฅผ ๋ถ๋ฆฌํ๋ ์ด์ ๋ ์๋ก์ ์์กด์ฑ์ ๋์ด๋ด๊ณ ๋ณ๊ฒฝ์ ์ํฅ์ ์ต์ํํ๊ธฐ ์ํจ์
๋๋ค.
๋ง์ฝ ๊ณ์ฐ๊ธฐ ๊ฐ์ฒด์ calEquation() ๋ฉ์๋์ ๋ค์ด๋ฐ์ด ๋ฐ๋๊ฒ ๋๋ค๋ฉด ResultView ์๋ ๋ณ๊ฒฝ์ด ์๊ธฐ์ง ์์๊น์?
```suggestion
public void viewResult(int result) {
System.out.println("๊ณ์ฐ ๊ฒฐ๊ณผ = " + result);
}
``` |
@@ -0,0 +1,75 @@
+package study;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.Test;
+
+public class SimpleCalculatorTest {
+
+ @Test
+ void plusTest() {
+ //given
+ String input = "10 + 5";
+ Equation equation = new Equation(input);
+ SimpleCalculator calculator = new SimpleCalculator(equation);
+
+ //when
+ int result = calculator.cal(
+ equation.getSymbolsList().get(0),
+ equation.getNumbers().get(0),
+ equation.getNumbers().get(1));
+
+ //then
+ assertThat(result).isEqualTo(15);
+ }
+
+ @Test
+ void minusTest() {
+ //given
+ String input = "10 - 5";
+ Equation equation = new Equation(input);
+ SimpleCalculator calculator = new SimpleCalculator(equation);
+
+ //when
+ int result = calculator.cal(
+ equation.getSymbolsList().get(0),
+ equation.getNumbers().get(0),
+ equation.getNumbers().get(1));
+
+ //then
+ assertThat(result).isEqualTo(5);
+ }
+
+ @Test
+ void multiplyTest() {
+ //given
+ String input = "10 * 5";
+ Equation equation = new Equation(input);
+ SimpleCalculator calculator = new SimpleCalculator(equation);
+ //when
+ int result = calculator.cal(
+ equation.getSymbolsList().get(0),
+ equation.getNumbers().get(0),
+ equation.getNumbers().get(1));
+
+ //then
+ assertThat(result).isEqualTo(50);
+ }
+
+ @Test
+ void divisionTest() {
+ //given
+ String input = "10 / 5";
+ Equation equation = new Equation(input);
+ SimpleCalculator calculator = new SimpleCalculator(equation);
+ //when
+ int result = calculator.cal(
+ equation.getSymbolsList().get(0),
+ equation.getNumbers().get(0),
+ equation.getNumbers().get(1));
+
+ //then
+ assertThat(result).isEqualTo(2);
+ }
+
+} | Java | ๊ณ์ฐ๊ธฐ ํ
์คํธ์๋ @DisplayNameย ์ด๋
ธํ
์ด์
์ ํ์ฉํ๋ฉด ๋ ๊ฐ๋
์ฑ ์๋ ํ
์คํธ ์ฝ๋๋ฅผ ์์ฑ ํ ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค :) |
@@ -0,0 +1,82 @@
+package study;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+public class Equation {
+
+ private final String equation;
+
+ private static final String INVALID_CALCULATION_FORMAT = "์๋ชป๋ ๊ณ์ฐ์์
๋๋ค.";
+ private static final String DELIMITER = " ";
+
+ public Equation(String equation) {
+ this.equation = equation;
+ checkEquation();
+ }
+
+ public void checkEquation() {
+ String[] split = equation.split(DELIMITER);
+
+ for (int i = 0; i < split.length; ) {
+ checkDoubleNumber(split, i);
+ i += 2;
+ }
+
+ for (int i = 1; i < split.length; ) {
+ checkDoubleSymbol(split, i);
+ i += 2;
+ }
+
+ }
+
+ public List<Integer> getNumbers() {
+ List<Integer> numList = new ArrayList<>();
+ String[] inputArr = equation.split(DELIMITER);
+ Arrays.stream(inputArr).filter(this::isParesInt).forEach(s -> addNumList(numList, s));
+ return numList;
+ }
+
+ public List<String> getSymbolsList() {
+ List<String> symbolList = new ArrayList<>();
+ String[] inputArr = equation.split(DELIMITER);
+ Arrays.stream(inputArr).filter(s -> !isParesInt(s))
+ .forEach(s -> addSymbolList(symbolList, s));
+ return symbolList;
+ }
+
+ private boolean isParesInt(String input) {
+ return input.chars().allMatch(Character::isDigit);
+ }
+
+ private void addNumList(List<Integer> numList, String input) {
+ numList.add(Integer.parseInt(input));
+ }
+
+ private void addSymbolList(List<String> symbolList, String input) {
+ checkSymbol(input);
+ symbolList.add(input);
+ }
+
+ private void checkSymbol(String input) {
+ if (!SymbolStatus.checkSymbol(input)) {
+ throw new IllegalStateException(INVALID_CALCULATION_FORMAT);
+ }
+ }
+
+ private void checkDoubleNumber(String[] split, int i) {
+ boolean parseInt = isParesInt(split[i]);
+ if (!parseInt) {
+ throw new IllegalStateException(INVALID_CALCULATION_FORMAT);
+ }
+ }
+
+ private void checkDoubleSymbol(String[] split, int i) {
+ boolean parse = isParesInt(split[i]);
+ if (parse) {
+ throw new IllegalStateException(INVALID_CALCULATION_FORMAT);
+ }
+ }
+
+} | Java | ์์์ ์ซ์๋ฅผ ์ฌ์ฉํ๋ ๋งค์ง ๋๋ฒ๋ ์์ค ์ฝ๋๋ฅผ ์ฝ๊ธฐ ์ด๋ ต๊ฒ ๋ง๋๋๋ฐ์ !
์ซ์ 2๋ ์ด๋ค ์๋ฏธ์ผ๊น์? |
@@ -0,0 +1,20 @@
+package study;
+
+import java.util.Scanner;
+
+public class Main {
+
+ public static void main(String[] args) {
+ ResultView resultView = new ResultView();
+
+ resultView.initStart();
+ Scanner scanner = new Scanner(System.in);
+ InputView inputView = new InputView(scanner);
+
+ Equation equation = new Equation(inputView.readEquation());
+ SimpleCalculator simpleCalculator = new SimpleCalculator(equation);
+
+ resultView.viewResult(simpleCalculator);
+
+ }
+} | Java | ํ์ผ ๋ง์ง๋ง์ ์ํฐ(๊ฐํ๋ฌธ์)๋ฅผ ๋ฃ์ด์ฃผ์ธ์ :)
์ด์ ๋ ๋ฆฌ๋ทฐ๋ฅผ ์งํํ ๋ ๊นํ๋ธ์์ ๊ฒฝ๊ณ ๋ฉ์์ง๋ฅผ ์ง์ฐ๊ณ ํน์ ๋ชจ๋ฅด๋ ํ์ผ ์ฝ๊ธฐ ์ค๋ฅ์ ๋๋นํ๊ธฐ ์ํจ์
๋๋ค.
์ข ๋ ์๊ณ ์ถ์ผ์๋ฉด ์ฐธ๊ณ ๋งํฌ๋ฅผ ๋ณด์
๋ ์ฌ๋ฐ์ ๊ฒ ๊ฐ๋ค์ :)
Intellij ๋ฅผ ์ฌ์ฉํ์ค ๊ฒฝ์ฐ์Preferences -> Editor -> General -> Ensure line feed at file end on save ๋ฅผ ์ฒดํฌํด์ฃผ์๋ฉดํ์ผ ์ ์ฅ ์ ๋ง์ง๋ง์ ๊ฐํ๋ฌธ์๋ฅผ ์๋์ผ๋ก ๋ฃ์ด์ค๋๋ค!
https://minz.dev/19https://stackoverflow.com/questions/729692/why-should-text-files-end-with-a-newline |
@@ -0,0 +1,52 @@
+package study;
+
+public class SimpleCalculator {
+
+ private final Equation equation;
+
+ private static final String NO_DIVIDE_BY_ZERO = "0์ผ๋ก ๋๋ ์ ์์ต๋๋ค.";
+
+ public SimpleCalculator(Equation equation) {
+ this.equation = equation;
+ }
+
+ public int cal(String symbol, Integer num1, Integer num2) {
+ if (symbol.equals(SymbolStatus.PLUS.toString())) {
+ return num1 + num2;
+ }
+
+ if (symbol.equals(SymbolStatus.MINUS.toString())) {
+ return num1 - num2;
+ }
+
+ if (symbol.equals(SymbolStatus.MULTIPLY.toString())) {
+ return num1 * num2;
+ }
+
+ if (symbol.equals(SymbolStatus.DIVISION.toString())) {
+ checkDivideByZero(num2);
+ return num1 / num2;
+ }
+
+ throw new IllegalStateException("์๋ชป ์
๋ ฅํ์
จ์ต๋๋ค..");
+ }
+
+ private void checkDivideByZero(Integer num) {
+ if (num == 0) {
+ throw new ArithmeticException(NO_DIVIDE_BY_ZERO);
+ }
+ }
+
+ public int calEquation() {
+ int cal = cal(
+ equation.getSymbolsList().get(0),
+ equation.getNumbers().get(0),
+ equation.getNumbers().get(1));
+
+ for (int i = 1; i < equation.getSymbolsList().size(); i++) {
+ cal = cal(equation.getSymbolsList().get(i), cal, equation.getNumbers().get(i + 1));
+ }
+
+ return cal;
+ }
+} | Java | `๊ณ์ฐ๊ธฐ`๊ฐ ํ๋์ `๋ฐฉ์ ์`์ ์ํ๋ก ๊ฐ์ง๋๋ก ๊ตฌํํ์
จ๋ค์ !
๊ณ์ฐ๊ธฐ๊ฐ ๋ ๋ค๋ฅธ ๋ฐฉ์ ์์ ๋ํ ๊ฐ์ ์ด๋ป๊ฒ ๊ตฌํ ์ ์์๊น์?
ํ์ฌ ์ํ์์๋ ํ๋์ ๊ณ์ฐ๊ธฐ ๊ฐ์ฒด๊ฐ ํ๋์ ๋ฐฉ์ ์๋ง์ ๊ณ์ฐํ ์ ์๋๋ฐ์. ์ฌ๋ฌ ๊ฐ์ ๋ฐฉ์ ์์ ๋ํด ๊ณ์ฐํ ์ ์๋๋ก ๊ฐ์ ํด๋ณด๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค :) |
@@ -0,0 +1,52 @@
+package study;
+
+public class SimpleCalculator {
+
+ private final Equation equation;
+
+ private static final String NO_DIVIDE_BY_ZERO = "0์ผ๋ก ๋๋ ์ ์์ต๋๋ค.";
+
+ public SimpleCalculator(Equation equation) {
+ this.equation = equation;
+ }
+
+ public int cal(String symbol, Integer num1, Integer num2) {
+ if (symbol.equals(SymbolStatus.PLUS.toString())) {
+ return num1 + num2;
+ }
+
+ if (symbol.equals(SymbolStatus.MINUS.toString())) {
+ return num1 - num2;
+ }
+
+ if (symbol.equals(SymbolStatus.MULTIPLY.toString())) {
+ return num1 * num2;
+ }
+
+ if (symbol.equals(SymbolStatus.DIVISION.toString())) {
+ checkDivideByZero(num2);
+ return num1 / num2;
+ }
+
+ throw new IllegalStateException("์๋ชป ์
๋ ฅํ์
จ์ต๋๋ค..");
+ }
+
+ private void checkDivideByZero(Integer num) {
+ if (num == 0) {
+ throw new ArithmeticException(NO_DIVIDE_BY_ZERO);
+ }
+ }
+
+ public int calEquation() {
+ int cal = cal(
+ equation.getSymbolsList().get(0),
+ equation.getNumbers().get(0),
+ equation.getNumbers().get(1));
+
+ for (int i = 1; i < equation.getSymbolsList().size(); i++) {
+ cal = cal(equation.getSymbolsList().get(i), cal, equation.getNumbers().get(i + 1));
+ }
+
+ return cal;
+ }
+} | Java | ๋ฉ์๋๋ ๋ณ์๋ช
์ ์ฝ์ด๋ฅผ ์ฌ์ฉํ๋ ๊ฒ์ ์ง์ํด์ฃผ์ธ์.
์ฝ์ด๋ ๋ณ๋์ ๊ท์ฝ์ผ๋ก ์ ํด์ง์ง ์์ผ๋ฉด ์์ค์ฝ๋์ ๊ฐ๋
์ฑ์ ์ด๋ ต๊ฒ ๋ง๋ญ๋๋ค :)
```suggestion
public int calculate(String symbol, Integer num1, Integer num2) {
``` |
@@ -0,0 +1,52 @@
+package study;
+
+public class SimpleCalculator {
+
+ private final Equation equation;
+
+ private static final String NO_DIVIDE_BY_ZERO = "0์ผ๋ก ๋๋ ์ ์์ต๋๋ค.";
+
+ public SimpleCalculator(Equation equation) {
+ this.equation = equation;
+ }
+
+ public int cal(String symbol, Integer num1, Integer num2) {
+ if (symbol.equals(SymbolStatus.PLUS.toString())) {
+ return num1 + num2;
+ }
+
+ if (symbol.equals(SymbolStatus.MINUS.toString())) {
+ return num1 - num2;
+ }
+
+ if (symbol.equals(SymbolStatus.MULTIPLY.toString())) {
+ return num1 * num2;
+ }
+
+ if (symbol.equals(SymbolStatus.DIVISION.toString())) {
+ checkDivideByZero(num2);
+ return num1 / num2;
+ }
+
+ throw new IllegalStateException("์๋ชป ์
๋ ฅํ์
จ์ต๋๋ค..");
+ }
+
+ private void checkDivideByZero(Integer num) {
+ if (num == 0) {
+ throw new ArithmeticException(NO_DIVIDE_BY_ZERO);
+ }
+ }
+
+ public int calEquation() {
+ int cal = cal(
+ equation.getSymbolsList().get(0),
+ equation.getNumbers().get(0),
+ equation.getNumbers().get(1));
+
+ for (int i = 1; i < equation.getSymbolsList().size(); i++) {
+ cal = cal(equation.getSymbolsList().get(i), cal, equation.getNumbers().get(i + 1));
+ }
+
+ return cal;
+ }
+} | Java | SymbolStatus enum ํด๋์ค๋ฅผ ๋ง๋ค์ด์ฃผ์
จ๋ค์ ๐
SymbolStatus๋ฅผ ํตํด ์ฐ์ฐ๊ธฐํธ์ `์ํ`๋ฅผ ํ ๊ณณ์์ ๊ด๋ฆฌํ๊ฒ ํด์ฃผ์
จ์ผ๋ ๊ณ์ฐ์ ํ๋ `ํ์`๋ ํจ๊ป enum์ ๊ตฌํํด๋ณด๋ฉด ์ด๋จ๊น์?
https://techblog.woowahan.com/2527/ |
@@ -0,0 +1,75 @@
+import pandas as pd
+import numpy as np
+
+#์ ์ถ์ ๋ฆฌ์คํธ(์๊ธฐ ์
๋ ฅ)
+videos = ['์กฐ์ฉ์', '์ ํํธ', '์ ์ฐ๋ฏผ', '์ฅ์งํฌ', '์์ฑ์', '์ด์น์', '์ด๋จ์ค', '์ค๋ค์', '์ค์ ๋ฆฌ๋', '์ ์์', '๋ฐฑ์กํ', '๋ฐ์๋น', '๊นํ์ฐ', '๊นํ์', '๊นํํธ', '๊นํ์ฐ', '๊น์์', '๊น์์ฐ', '๊น์ธํ', '๊ฐ์งํธ', '๊ฐ์ํ']
+#Urclass ์๊ฐ์ ํํฉ csv ๋ถ๋ฌ์ค๊ธฐ
+df = pd.read_csv('1012.csv')
+
+def group_maker(random_seed, video=len(videos), videos=videos, ur_list=df, group_num=7):
+ """
+ ์ธ์ ๋ฐฐ์น๋ ๋๋ค์ด๋ ๊ฐ ์กฐ์ ์ ์ถ์์ ์๊ฐ ์ผ์ ํ๊ฒ ๋ค์ด๊ฐ๊ฒ๋ ํ๋ก์ ํธ ์กฐ ์ง๋ ํจ์์
๋๋ค
+
+ --ํ๋ผ๋ฏธํฐ--
+ * Random seed
+ * video = ์ค์ ์ ์ถ์ ์ (int) -> ์ ์ถ์ ๋ช
๋จ์ด ์ ์
๋ ฅ๋๋ ํ์ธํ๊ธฐ ์ํจ
+ * videos = ์ ์ถ์ ๋ช
๋จ (list)
+ * ur_list = Urclass์์ exportํ ๊ธฐ์ ๋ช
๋จ (dataframe)
+ * group_num = ์กฐ ์ (int)
+ """
+ try:
+ assert len(videos) == video #์ ์ถ์ ๋ช
๋จ์ด ์ ์
๋ ฅ๋์๋์ง ํ์ธ
+
+ #๋ฏธ์ ์ถ์ ๋ฆฌ์คํธ
+ non_videos = [name for name in ur_list['์ด๋ฆ'].values if name not in videos]
+
+ try: #๋ฏธ์ ์ถ์ ๋ฆฌ์คํธ๊ฐ ์ ๋ฝํ๋์ง ํ์ธ (ํ๊ธ์ด๋ผ ์๋ชป ๋ฝํ๋ ๊ฒฝ์ฐ ์์)
+ assert len(videos) + len(non_videos) == len(ur_list)
+
+ #์กฐ ๋ฐฐ์ ์์!
+ np.random.seed(random_seed)
+ np.random.shuffle(videos)
+ np.random.shuffle(non_videos)
+
+ video = int(len(videos)/group_num) #ํ ์กฐ ์ต์ ์ ์ถ์ ์ธ์
+ non_video = int(len(non_videos)/group_num) #ํ ์กฐ ์ต์ ๋ฏธ์ ์ถ์ ์ธ์
+ groups = {}
+
+ for i in range(group_num+1):
+ if i == group_num:
+ #1์กฐ๋ถํฐ ๋ฏธ์ ์ถ์ ๋๋จธ์ง ์ธ์ ๋ฐฐ์น
+ for j in range(len(non_videos[non_video*i:])):
+ groups[f'{j+1}์กฐ'].append(non_videos.pop())
+
+ #๋ท ์กฐ๋ถํฐ ์ ์ถ์ ๋๋จธ์ง ์ธ์ ๋ฐฐ์น
+ for j in range(len(videos[video*i:])):
+ groups[f'{group_num-j}์กฐ'].append(videos.pop())
+
+ return groups
+
+ group = videos[video*i:video*(i+1)]
+ group = group + non_videos[non_video*i:non_video*(i+1)]
+ groups[f'{i+1}์กฐ'] = group
+
+ except:
+ print(f'๋ฏธ ์ ์ถ์ ๋ฆฌ์คํธ๋ฅผ ํ์ธํ์ธ์')
+ print(f'\t* ์ด ์ธ์ ์: {len(ur_list)}๋ช
, \n\t* ๋ฏธ ์ ์ถ์ ๋ฆฌ์คํธ: {len(non_videos)}๋ช
, \n{non_videos}, \n\t* ์ ์ถ์ ๋ฆฌ์คํธ: {len(videos)}๋ช
, {videos}')
+
+ except:
+ print('์
๋ ฅํ ์ ์ถ์ ์ธ์ ์์ ์ ์ถ์ ๋ช
๋จ์ ์๋ ์๊ฐ ์ผ์นํ์ง ์์ต๋๋ค. ์ ์ถ์ ๋ช
๋จ์ ํ์ธํด ์ฃผ์ธ์')
+
+if __name__ == "__main__":
+ #๊ทธ๋ฃน ๋ง๋ค๊ธฐ
+ groups = group_maker(random_seed=1012, video=21)
+
+ #๋ช
๋จ ์ถ๋ ฅ
+ for group in groups:
+ print(groups.get(group))
+
+ #์๊ฐ์ ์ด๋ฆ์ด ๋น ์ง์์ด ๋ค์ด๊ฐ๋์ง ์ฌํ์ธ
+ j=0
+ for group in groups:
+ i = len(groups.get(group))
+ j += i
+
+ assert j == len(df) | Python | read_csv ๋ฅผ ์ด์ฉํด์ list ๋ก ์ฝ๊ธฐ ์ํจ์ด๋ผ๋ฉด, csv reader ๋ฅผ ์ฌ์ฉํ์๋๊ฑด ์ด๋จ๊น์?
`import pandas` ๋ฅผ ํ๋ ค๋ฉด 45MB ์ ๋์ pandas ๊ฐ ํ์ํ๋์ csv ๋ฅผ ์ฌ์ฉํ๋ฉด 16KB ๋ง์ ํด๊ฒฐํ ์ ์์ต๋๋ค! |
@@ -0,0 +1,75 @@
+import pandas as pd
+import numpy as np
+
+#์ ์ถ์ ๋ฆฌ์คํธ(์๊ธฐ ์
๋ ฅ)
+videos = ['์กฐ์ฉ์', '์ ํํธ', '์ ์ฐ๋ฏผ', '์ฅ์งํฌ', '์์ฑ์', '์ด์น์', '์ด๋จ์ค', '์ค๋ค์', '์ค์ ๋ฆฌ๋', '์ ์์', '๋ฐฑ์กํ', '๋ฐ์๋น', '๊นํ์ฐ', '๊นํ์', '๊นํํธ', '๊นํ์ฐ', '๊น์์', '๊น์์ฐ', '๊น์ธํ', '๊ฐ์งํธ', '๊ฐ์ํ']
+#Urclass ์๊ฐ์ ํํฉ csv ๋ถ๋ฌ์ค๊ธฐ
+df = pd.read_csv('1012.csv')
+
+def group_maker(random_seed, video=len(videos), videos=videos, ur_list=df, group_num=7):
+ """
+ ์ธ์ ๋ฐฐ์น๋ ๋๋ค์ด๋ ๊ฐ ์กฐ์ ์ ์ถ์์ ์๊ฐ ์ผ์ ํ๊ฒ ๋ค์ด๊ฐ๊ฒ๋ ํ๋ก์ ํธ ์กฐ ์ง๋ ํจ์์
๋๋ค
+
+ --ํ๋ผ๋ฏธํฐ--
+ * Random seed
+ * video = ์ค์ ์ ์ถ์ ์ (int) -> ์ ์ถ์ ๋ช
๋จ์ด ์ ์
๋ ฅ๋๋ ํ์ธํ๊ธฐ ์ํจ
+ * videos = ์ ์ถ์ ๋ช
๋จ (list)
+ * ur_list = Urclass์์ exportํ ๊ธฐ์ ๋ช
๋จ (dataframe)
+ * group_num = ์กฐ ์ (int)
+ """
+ try:
+ assert len(videos) == video #์ ์ถ์ ๋ช
๋จ์ด ์ ์
๋ ฅ๋์๋์ง ํ์ธ
+
+ #๋ฏธ์ ์ถ์ ๋ฆฌ์คํธ
+ non_videos = [name for name in ur_list['์ด๋ฆ'].values if name not in videos]
+
+ try: #๋ฏธ์ ์ถ์ ๋ฆฌ์คํธ๊ฐ ์ ๋ฝํ๋์ง ํ์ธ (ํ๊ธ์ด๋ผ ์๋ชป ๋ฝํ๋ ๊ฒฝ์ฐ ์์)
+ assert len(videos) + len(non_videos) == len(ur_list)
+
+ #์กฐ ๋ฐฐ์ ์์!
+ np.random.seed(random_seed)
+ np.random.shuffle(videos)
+ np.random.shuffle(non_videos)
+
+ video = int(len(videos)/group_num) #ํ ์กฐ ์ต์ ์ ์ถ์ ์ธ์
+ non_video = int(len(non_videos)/group_num) #ํ ์กฐ ์ต์ ๋ฏธ์ ์ถ์ ์ธ์
+ groups = {}
+
+ for i in range(group_num+1):
+ if i == group_num:
+ #1์กฐ๋ถํฐ ๋ฏธ์ ์ถ์ ๋๋จธ์ง ์ธ์ ๋ฐฐ์น
+ for j in range(len(non_videos[non_video*i:])):
+ groups[f'{j+1}์กฐ'].append(non_videos.pop())
+
+ #๋ท ์กฐ๋ถํฐ ์ ์ถ์ ๋๋จธ์ง ์ธ์ ๋ฐฐ์น
+ for j in range(len(videos[video*i:])):
+ groups[f'{group_num-j}์กฐ'].append(videos.pop())
+
+ return groups
+
+ group = videos[video*i:video*(i+1)]
+ group = group + non_videos[non_video*i:non_video*(i+1)]
+ groups[f'{i+1}์กฐ'] = group
+
+ except:
+ print(f'๋ฏธ ์ ์ถ์ ๋ฆฌ์คํธ๋ฅผ ํ์ธํ์ธ์')
+ print(f'\t* ์ด ์ธ์ ์: {len(ur_list)}๋ช
, \n\t* ๋ฏธ ์ ์ถ์ ๋ฆฌ์คํธ: {len(non_videos)}๋ช
, \n{non_videos}, \n\t* ์ ์ถ์ ๋ฆฌ์คํธ: {len(videos)}๋ช
, {videos}')
+
+ except:
+ print('์
๋ ฅํ ์ ์ถ์ ์ธ์ ์์ ์ ์ถ์ ๋ช
๋จ์ ์๋ ์๊ฐ ์ผ์นํ์ง ์์ต๋๋ค. ์ ์ถ์ ๋ช
๋จ์ ํ์ธํด ์ฃผ์ธ์')
+
+if __name__ == "__main__":
+ #๊ทธ๋ฃน ๋ง๋ค๊ธฐ
+ groups = group_maker(random_seed=1012, video=21)
+
+ #๋ช
๋จ ์ถ๋ ฅ
+ for group in groups:
+ print(groups.get(group))
+
+ #์๊ฐ์ ์ด๋ฆ์ด ๋น ์ง์์ด ๋ค์ด๊ฐ๋์ง ์ฌํ์ธ
+ j=0
+ for group in groups:
+ i = len(groups.get(group))
+ j += i
+
+ assert j == len(df) | Python | numpy ๋ 23 MB ์
๋๋ค. python ์ ๊ธฐ๋ณธ์ผ๋ก ๋ค์ด๊ฐ์๋ random ๋ชจ๋์ ์ฌ์ฉํ์๋๊ฑด ์ด๋จ๊น์? |
@@ -0,0 +1,75 @@
+import pandas as pd
+import numpy as np
+
+#์ ์ถ์ ๋ฆฌ์คํธ(์๊ธฐ ์
๋ ฅ)
+videos = ['์กฐ์ฉ์', '์ ํํธ', '์ ์ฐ๋ฏผ', '์ฅ์งํฌ', '์์ฑ์', '์ด์น์', '์ด๋จ์ค', '์ค๋ค์', '์ค์ ๋ฆฌ๋', '์ ์์', '๋ฐฑ์กํ', '๋ฐ์๋น', '๊นํ์ฐ', '๊นํ์', '๊นํํธ', '๊นํ์ฐ', '๊น์์', '๊น์์ฐ', '๊น์ธํ', '๊ฐ์งํธ', '๊ฐ์ํ']
+#Urclass ์๊ฐ์ ํํฉ csv ๋ถ๋ฌ์ค๊ธฐ
+df = pd.read_csv('1012.csv')
+
+def group_maker(random_seed, video=len(videos), videos=videos, ur_list=df, group_num=7):
+ """
+ ์ธ์ ๋ฐฐ์น๋ ๋๋ค์ด๋ ๊ฐ ์กฐ์ ์ ์ถ์์ ์๊ฐ ์ผ์ ํ๊ฒ ๋ค์ด๊ฐ๊ฒ๋ ํ๋ก์ ํธ ์กฐ ์ง๋ ํจ์์
๋๋ค
+
+ --ํ๋ผ๋ฏธํฐ--
+ * Random seed
+ * video = ์ค์ ์ ์ถ์ ์ (int) -> ์ ์ถ์ ๋ช
๋จ์ด ์ ์
๋ ฅ๋๋ ํ์ธํ๊ธฐ ์ํจ
+ * videos = ์ ์ถ์ ๋ช
๋จ (list)
+ * ur_list = Urclass์์ exportํ ๊ธฐ์ ๋ช
๋จ (dataframe)
+ * group_num = ์กฐ ์ (int)
+ """
+ try:
+ assert len(videos) == video #์ ์ถ์ ๋ช
๋จ์ด ์ ์
๋ ฅ๋์๋์ง ํ์ธ
+
+ #๋ฏธ์ ์ถ์ ๋ฆฌ์คํธ
+ non_videos = [name for name in ur_list['์ด๋ฆ'].values if name not in videos]
+
+ try: #๋ฏธ์ ์ถ์ ๋ฆฌ์คํธ๊ฐ ์ ๋ฝํ๋์ง ํ์ธ (ํ๊ธ์ด๋ผ ์๋ชป ๋ฝํ๋ ๊ฒฝ์ฐ ์์)
+ assert len(videos) + len(non_videos) == len(ur_list)
+
+ #์กฐ ๋ฐฐ์ ์์!
+ np.random.seed(random_seed)
+ np.random.shuffle(videos)
+ np.random.shuffle(non_videos)
+
+ video = int(len(videos)/group_num) #ํ ์กฐ ์ต์ ์ ์ถ์ ์ธ์
+ non_video = int(len(non_videos)/group_num) #ํ ์กฐ ์ต์ ๋ฏธ์ ์ถ์ ์ธ์
+ groups = {}
+
+ for i in range(group_num+1):
+ if i == group_num:
+ #1์กฐ๋ถํฐ ๋ฏธ์ ์ถ์ ๋๋จธ์ง ์ธ์ ๋ฐฐ์น
+ for j in range(len(non_videos[non_video*i:])):
+ groups[f'{j+1}์กฐ'].append(non_videos.pop())
+
+ #๋ท ์กฐ๋ถํฐ ์ ์ถ์ ๋๋จธ์ง ์ธ์ ๋ฐฐ์น
+ for j in range(len(videos[video*i:])):
+ groups[f'{group_num-j}์กฐ'].append(videos.pop())
+
+ return groups
+
+ group = videos[video*i:video*(i+1)]
+ group = group + non_videos[non_video*i:non_video*(i+1)]
+ groups[f'{i+1}์กฐ'] = group
+
+ except:
+ print(f'๋ฏธ ์ ์ถ์ ๋ฆฌ์คํธ๋ฅผ ํ์ธํ์ธ์')
+ print(f'\t* ์ด ์ธ์ ์: {len(ur_list)}๋ช
, \n\t* ๋ฏธ ์ ์ถ์ ๋ฆฌ์คํธ: {len(non_videos)}๋ช
, \n{non_videos}, \n\t* ์ ์ถ์ ๋ฆฌ์คํธ: {len(videos)}๋ช
, {videos}')
+
+ except:
+ print('์
๋ ฅํ ์ ์ถ์ ์ธ์ ์์ ์ ์ถ์ ๋ช
๋จ์ ์๋ ์๊ฐ ์ผ์นํ์ง ์์ต๋๋ค. ์ ์ถ์ ๋ช
๋จ์ ํ์ธํด ์ฃผ์ธ์')
+
+if __name__ == "__main__":
+ #๊ทธ๋ฃน ๋ง๋ค๊ธฐ
+ groups = group_maker(random_seed=1012, video=21)
+
+ #๋ช
๋จ ์ถ๋ ฅ
+ for group in groups:
+ print(groups.get(group))
+
+ #์๊ฐ์ ์ด๋ฆ์ด ๋น ์ง์์ด ๋ค์ด๊ฐ๋์ง ์ฌํ์ธ
+ j=0
+ for group in groups:
+ i = len(groups.get(group))
+ j += i
+
+ assert j == len(df) | Python | csv ํ์ผ์ ์ฝ๋ ๋ถ๋ถ์ ํจ์๋ก ๋ง๋ค๋ฉด ์ฌ์ฌ์ฉํ๊ธฐ ๋ ํธ๋ฆฌํ ๋ฏํฉ๋๋ค. |
@@ -0,0 +1,75 @@
+import pandas as pd
+import numpy as np
+
+#์ ์ถ์ ๋ฆฌ์คํธ(์๊ธฐ ์
๋ ฅ)
+videos = ['์กฐ์ฉ์', '์ ํํธ', '์ ์ฐ๋ฏผ', '์ฅ์งํฌ', '์์ฑ์', '์ด์น์', '์ด๋จ์ค', '์ค๋ค์', '์ค์ ๋ฆฌ๋', '์ ์์', '๋ฐฑ์กํ', '๋ฐ์๋น', '๊นํ์ฐ', '๊นํ์', '๊นํํธ', '๊นํ์ฐ', '๊น์์', '๊น์์ฐ', '๊น์ธํ', '๊ฐ์งํธ', '๊ฐ์ํ']
+#Urclass ์๊ฐ์ ํํฉ csv ๋ถ๋ฌ์ค๊ธฐ
+df = pd.read_csv('1012.csv')
+
+def group_maker(random_seed, video=len(videos), videos=videos, ur_list=df, group_num=7):
+ """
+ ์ธ์ ๋ฐฐ์น๋ ๋๋ค์ด๋ ๊ฐ ์กฐ์ ์ ์ถ์์ ์๊ฐ ์ผ์ ํ๊ฒ ๋ค์ด๊ฐ๊ฒ๋ ํ๋ก์ ํธ ์กฐ ์ง๋ ํจ์์
๋๋ค
+
+ --ํ๋ผ๋ฏธํฐ--
+ * Random seed
+ * video = ์ค์ ์ ์ถ์ ์ (int) -> ์ ์ถ์ ๋ช
๋จ์ด ์ ์
๋ ฅ๋๋ ํ์ธํ๊ธฐ ์ํจ
+ * videos = ์ ์ถ์ ๋ช
๋จ (list)
+ * ur_list = Urclass์์ exportํ ๊ธฐ์ ๋ช
๋จ (dataframe)
+ * group_num = ์กฐ ์ (int)
+ """
+ try:
+ assert len(videos) == video #์ ์ถ์ ๋ช
๋จ์ด ์ ์
๋ ฅ๋์๋์ง ํ์ธ
+
+ #๋ฏธ์ ์ถ์ ๋ฆฌ์คํธ
+ non_videos = [name for name in ur_list['์ด๋ฆ'].values if name not in videos]
+
+ try: #๋ฏธ์ ์ถ์ ๋ฆฌ์คํธ๊ฐ ์ ๋ฝํ๋์ง ํ์ธ (ํ๊ธ์ด๋ผ ์๋ชป ๋ฝํ๋ ๊ฒฝ์ฐ ์์)
+ assert len(videos) + len(non_videos) == len(ur_list)
+
+ #์กฐ ๋ฐฐ์ ์์!
+ np.random.seed(random_seed)
+ np.random.shuffle(videos)
+ np.random.shuffle(non_videos)
+
+ video = int(len(videos)/group_num) #ํ ์กฐ ์ต์ ์ ์ถ์ ์ธ์
+ non_video = int(len(non_videos)/group_num) #ํ ์กฐ ์ต์ ๋ฏธ์ ์ถ์ ์ธ์
+ groups = {}
+
+ for i in range(group_num+1):
+ if i == group_num:
+ #1์กฐ๋ถํฐ ๋ฏธ์ ์ถ์ ๋๋จธ์ง ์ธ์ ๋ฐฐ์น
+ for j in range(len(non_videos[non_video*i:])):
+ groups[f'{j+1}์กฐ'].append(non_videos.pop())
+
+ #๋ท ์กฐ๋ถํฐ ์ ์ถ์ ๋๋จธ์ง ์ธ์ ๋ฐฐ์น
+ for j in range(len(videos[video*i:])):
+ groups[f'{group_num-j}์กฐ'].append(videos.pop())
+
+ return groups
+
+ group = videos[video*i:video*(i+1)]
+ group = group + non_videos[non_video*i:non_video*(i+1)]
+ groups[f'{i+1}์กฐ'] = group
+
+ except:
+ print(f'๋ฏธ ์ ์ถ์ ๋ฆฌ์คํธ๋ฅผ ํ์ธํ์ธ์')
+ print(f'\t* ์ด ์ธ์ ์: {len(ur_list)}๋ช
, \n\t* ๋ฏธ ์ ์ถ์ ๋ฆฌ์คํธ: {len(non_videos)}๋ช
, \n{non_videos}, \n\t* ์ ์ถ์ ๋ฆฌ์คํธ: {len(videos)}๋ช
, {videos}')
+
+ except:
+ print('์
๋ ฅํ ์ ์ถ์ ์ธ์ ์์ ์ ์ถ์ ๋ช
๋จ์ ์๋ ์๊ฐ ์ผ์นํ์ง ์์ต๋๋ค. ์ ์ถ์ ๋ช
๋จ์ ํ์ธํด ์ฃผ์ธ์')
+
+if __name__ == "__main__":
+ #๊ทธ๋ฃน ๋ง๋ค๊ธฐ
+ groups = group_maker(random_seed=1012, video=21)
+
+ #๋ช
๋จ ์ถ๋ ฅ
+ for group in groups:
+ print(groups.get(group))
+
+ #์๊ฐ์ ์ด๋ฆ์ด ๋น ์ง์์ด ๋ค์ด๊ฐ๋์ง ์ฌํ์ธ
+ j=0
+ for group in groups:
+ i = len(groups.get(group))
+ j += i
+
+ assert j == len(df) | Python | ํ๋์ ํจ์์๋ ํ๋์ ๋ก์ง์ด ๋ค์ด๊ฐ ์ ์๋๋ก ๋ณ๊ฒฝํด๋ณด๋๊ฑด ์ด๋จ๊น์? |
@@ -0,0 +1,75 @@
+import pandas as pd
+import numpy as np
+
+#์ ์ถ์ ๋ฆฌ์คํธ(์๊ธฐ ์
๋ ฅ)
+videos = ['์กฐ์ฉ์', '์ ํํธ', '์ ์ฐ๋ฏผ', '์ฅ์งํฌ', '์์ฑ์', '์ด์น์', '์ด๋จ์ค', '์ค๋ค์', '์ค์ ๋ฆฌ๋', '์ ์์', '๋ฐฑ์กํ', '๋ฐ์๋น', '๊นํ์ฐ', '๊นํ์', '๊นํํธ', '๊นํ์ฐ', '๊น์์', '๊น์์ฐ', '๊น์ธํ', '๊ฐ์งํธ', '๊ฐ์ํ']
+#Urclass ์๊ฐ์ ํํฉ csv ๋ถ๋ฌ์ค๊ธฐ
+df = pd.read_csv('1012.csv')
+
+def group_maker(random_seed, video=len(videos), videos=videos, ur_list=df, group_num=7):
+ """
+ ์ธ์ ๋ฐฐ์น๋ ๋๋ค์ด๋ ๊ฐ ์กฐ์ ์ ์ถ์์ ์๊ฐ ์ผ์ ํ๊ฒ ๋ค์ด๊ฐ๊ฒ๋ ํ๋ก์ ํธ ์กฐ ์ง๋ ํจ์์
๋๋ค
+
+ --ํ๋ผ๋ฏธํฐ--
+ * Random seed
+ * video = ์ค์ ์ ์ถ์ ์ (int) -> ์ ์ถ์ ๋ช
๋จ์ด ์ ์
๋ ฅ๋๋ ํ์ธํ๊ธฐ ์ํจ
+ * videos = ์ ์ถ์ ๋ช
๋จ (list)
+ * ur_list = Urclass์์ exportํ ๊ธฐ์ ๋ช
๋จ (dataframe)
+ * group_num = ์กฐ ์ (int)
+ """
+ try:
+ assert len(videos) == video #์ ์ถ์ ๋ช
๋จ์ด ์ ์
๋ ฅ๋์๋์ง ํ์ธ
+
+ #๋ฏธ์ ์ถ์ ๋ฆฌ์คํธ
+ non_videos = [name for name in ur_list['์ด๋ฆ'].values if name not in videos]
+
+ try: #๋ฏธ์ ์ถ์ ๋ฆฌ์คํธ๊ฐ ์ ๋ฝํ๋์ง ํ์ธ (ํ๊ธ์ด๋ผ ์๋ชป ๋ฝํ๋ ๊ฒฝ์ฐ ์์)
+ assert len(videos) + len(non_videos) == len(ur_list)
+
+ #์กฐ ๋ฐฐ์ ์์!
+ np.random.seed(random_seed)
+ np.random.shuffle(videos)
+ np.random.shuffle(non_videos)
+
+ video = int(len(videos)/group_num) #ํ ์กฐ ์ต์ ์ ์ถ์ ์ธ์
+ non_video = int(len(non_videos)/group_num) #ํ ์กฐ ์ต์ ๋ฏธ์ ์ถ์ ์ธ์
+ groups = {}
+
+ for i in range(group_num+1):
+ if i == group_num:
+ #1์กฐ๋ถํฐ ๋ฏธ์ ์ถ์ ๋๋จธ์ง ์ธ์ ๋ฐฐ์น
+ for j in range(len(non_videos[non_video*i:])):
+ groups[f'{j+1}์กฐ'].append(non_videos.pop())
+
+ #๋ท ์กฐ๋ถํฐ ์ ์ถ์ ๋๋จธ์ง ์ธ์ ๋ฐฐ์น
+ for j in range(len(videos[video*i:])):
+ groups[f'{group_num-j}์กฐ'].append(videos.pop())
+
+ return groups
+
+ group = videos[video*i:video*(i+1)]
+ group = group + non_videos[non_video*i:non_video*(i+1)]
+ groups[f'{i+1}์กฐ'] = group
+
+ except:
+ print(f'๋ฏธ ์ ์ถ์ ๋ฆฌ์คํธ๋ฅผ ํ์ธํ์ธ์')
+ print(f'\t* ์ด ์ธ์ ์: {len(ur_list)}๋ช
, \n\t* ๋ฏธ ์ ์ถ์ ๋ฆฌ์คํธ: {len(non_videos)}๋ช
, \n{non_videos}, \n\t* ์ ์ถ์ ๋ฆฌ์คํธ: {len(videos)}๋ช
, {videos}')
+
+ except:
+ print('์
๋ ฅํ ์ ์ถ์ ์ธ์ ์์ ์ ์ถ์ ๋ช
๋จ์ ์๋ ์๊ฐ ์ผ์นํ์ง ์์ต๋๋ค. ์ ์ถ์ ๋ช
๋จ์ ํ์ธํด ์ฃผ์ธ์')
+
+if __name__ == "__main__":
+ #๊ทธ๋ฃน ๋ง๋ค๊ธฐ
+ groups = group_maker(random_seed=1012, video=21)
+
+ #๋ช
๋จ ์ถ๋ ฅ
+ for group in groups:
+ print(groups.get(group))
+
+ #์๊ฐ์ ์ด๋ฆ์ด ๋น ์ง์์ด ๋ค์ด๊ฐ๋์ง ์ฌํ์ธ
+ j=0
+ for group in groups:
+ i = len(groups.get(group))
+ j += i
+
+ assert j == len(df) | Python | ์ด๋ค ์๋ฌ๊ฐ ๋ฐ์ํ์๊น์? ์๋ฌ๋ฅผ ํ์ธํด๋ณด๊ณ `except {??Exception}` ์ผ๋ก ๊ด๋ฆฌํด์ฃผ์ ๋ค๋ฉด ์๋ฌ๊ด๋ฆฌํ๊ธฐ ๋ ์์ํ ๊ฒ์ผ๋ก ๋ณด์
๋๋ค ! |
@@ -0,0 +1,75 @@
+import pandas as pd
+import numpy as np
+
+#์ ์ถ์ ๋ฆฌ์คํธ(์๊ธฐ ์
๋ ฅ)
+videos = ['์กฐ์ฉ์', '์ ํํธ', '์ ์ฐ๋ฏผ', '์ฅ์งํฌ', '์์ฑ์', '์ด์น์', '์ด๋จ์ค', '์ค๋ค์', '์ค์ ๋ฆฌ๋', '์ ์์', '๋ฐฑ์กํ', '๋ฐ์๋น', '๊นํ์ฐ', '๊นํ์', '๊นํํธ', '๊นํ์ฐ', '๊น์์', '๊น์์ฐ', '๊น์ธํ', '๊ฐ์งํธ', '๊ฐ์ํ']
+#Urclass ์๊ฐ์ ํํฉ csv ๋ถ๋ฌ์ค๊ธฐ
+df = pd.read_csv('1012.csv')
+
+def group_maker(random_seed, video=len(videos), videos=videos, ur_list=df, group_num=7):
+ """
+ ์ธ์ ๋ฐฐ์น๋ ๋๋ค์ด๋ ๊ฐ ์กฐ์ ์ ์ถ์์ ์๊ฐ ์ผ์ ํ๊ฒ ๋ค์ด๊ฐ๊ฒ๋ ํ๋ก์ ํธ ์กฐ ์ง๋ ํจ์์
๋๋ค
+
+ --ํ๋ผ๋ฏธํฐ--
+ * Random seed
+ * video = ์ค์ ์ ์ถ์ ์ (int) -> ์ ์ถ์ ๋ช
๋จ์ด ์ ์
๋ ฅ๋๋ ํ์ธํ๊ธฐ ์ํจ
+ * videos = ์ ์ถ์ ๋ช
๋จ (list)
+ * ur_list = Urclass์์ exportํ ๊ธฐ์ ๋ช
๋จ (dataframe)
+ * group_num = ์กฐ ์ (int)
+ """
+ try:
+ assert len(videos) == video #์ ์ถ์ ๋ช
๋จ์ด ์ ์
๋ ฅ๋์๋์ง ํ์ธ
+
+ #๋ฏธ์ ์ถ์ ๋ฆฌ์คํธ
+ non_videos = [name for name in ur_list['์ด๋ฆ'].values if name not in videos]
+
+ try: #๋ฏธ์ ์ถ์ ๋ฆฌ์คํธ๊ฐ ์ ๋ฝํ๋์ง ํ์ธ (ํ๊ธ์ด๋ผ ์๋ชป ๋ฝํ๋ ๊ฒฝ์ฐ ์์)
+ assert len(videos) + len(non_videos) == len(ur_list)
+
+ #์กฐ ๋ฐฐ์ ์์!
+ np.random.seed(random_seed)
+ np.random.shuffle(videos)
+ np.random.shuffle(non_videos)
+
+ video = int(len(videos)/group_num) #ํ ์กฐ ์ต์ ์ ์ถ์ ์ธ์
+ non_video = int(len(non_videos)/group_num) #ํ ์กฐ ์ต์ ๋ฏธ์ ์ถ์ ์ธ์
+ groups = {}
+
+ for i in range(group_num+1):
+ if i == group_num:
+ #1์กฐ๋ถํฐ ๋ฏธ์ ์ถ์ ๋๋จธ์ง ์ธ์ ๋ฐฐ์น
+ for j in range(len(non_videos[non_video*i:])):
+ groups[f'{j+1}์กฐ'].append(non_videos.pop())
+
+ #๋ท ์กฐ๋ถํฐ ์ ์ถ์ ๋๋จธ์ง ์ธ์ ๋ฐฐ์น
+ for j in range(len(videos[video*i:])):
+ groups[f'{group_num-j}์กฐ'].append(videos.pop())
+
+ return groups
+
+ group = videos[video*i:video*(i+1)]
+ group = group + non_videos[non_video*i:non_video*(i+1)]
+ groups[f'{i+1}์กฐ'] = group
+
+ except:
+ print(f'๋ฏธ ์ ์ถ์ ๋ฆฌ์คํธ๋ฅผ ํ์ธํ์ธ์')
+ print(f'\t* ์ด ์ธ์ ์: {len(ur_list)}๋ช
, \n\t* ๋ฏธ ์ ์ถ์ ๋ฆฌ์คํธ: {len(non_videos)}๋ช
, \n{non_videos}, \n\t* ์ ์ถ์ ๋ฆฌ์คํธ: {len(videos)}๋ช
, {videos}')
+
+ except:
+ print('์
๋ ฅํ ์ ์ถ์ ์ธ์ ์์ ์ ์ถ์ ๋ช
๋จ์ ์๋ ์๊ฐ ์ผ์นํ์ง ์์ต๋๋ค. ์ ์ถ์ ๋ช
๋จ์ ํ์ธํด ์ฃผ์ธ์')
+
+if __name__ == "__main__":
+ #๊ทธ๋ฃน ๋ง๋ค๊ธฐ
+ groups = group_maker(random_seed=1012, video=21)
+
+ #๋ช
๋จ ์ถ๋ ฅ
+ for group in groups:
+ print(groups.get(group))
+
+ #์๊ฐ์ ์ด๋ฆ์ด ๋น ์ง์์ด ๋ค์ด๊ฐ๋์ง ์ฌํ์ธ
+ j=0
+ for group in groups:
+ i = len(groups.get(group))
+ j += i
+
+ assert j == len(df) | Python | ์ด๋ค ์๋ฌ๊ฐ ๋ฐ์ํ๋์ง ์ถ๊ฐํด์ฃผ์๋ฉด ์ข์๋ฏํฉ๋๋ค. |
@@ -0,0 +1,75 @@
+import pandas as pd
+import numpy as np
+
+#์ ์ถ์ ๋ฆฌ์คํธ(์๊ธฐ ์
๋ ฅ)
+videos = ['์กฐ์ฉ์', '์ ํํธ', '์ ์ฐ๋ฏผ', '์ฅ์งํฌ', '์์ฑ์', '์ด์น์', '์ด๋จ์ค', '์ค๋ค์', '์ค์ ๋ฆฌ๋', '์ ์์', '๋ฐฑ์กํ', '๋ฐ์๋น', '๊นํ์ฐ', '๊นํ์', '๊นํํธ', '๊นํ์ฐ', '๊น์์', '๊น์์ฐ', '๊น์ธํ', '๊ฐ์งํธ', '๊ฐ์ํ']
+#Urclass ์๊ฐ์ ํํฉ csv ๋ถ๋ฌ์ค๊ธฐ
+df = pd.read_csv('1012.csv')
+
+def group_maker(random_seed, video=len(videos), videos=videos, ur_list=df, group_num=7):
+ """
+ ์ธ์ ๋ฐฐ์น๋ ๋๋ค์ด๋ ๊ฐ ์กฐ์ ์ ์ถ์์ ์๊ฐ ์ผ์ ํ๊ฒ ๋ค์ด๊ฐ๊ฒ๋ ํ๋ก์ ํธ ์กฐ ์ง๋ ํจ์์
๋๋ค
+
+ --ํ๋ผ๋ฏธํฐ--
+ * Random seed
+ * video = ์ค์ ์ ์ถ์ ์ (int) -> ์ ์ถ์ ๋ช
๋จ์ด ์ ์
๋ ฅ๋๋ ํ์ธํ๊ธฐ ์ํจ
+ * videos = ์ ์ถ์ ๋ช
๋จ (list)
+ * ur_list = Urclass์์ exportํ ๊ธฐ์ ๋ช
๋จ (dataframe)
+ * group_num = ์กฐ ์ (int)
+ """
+ try:
+ assert len(videos) == video #์ ์ถ์ ๋ช
๋จ์ด ์ ์
๋ ฅ๋์๋์ง ํ์ธ
+
+ #๋ฏธ์ ์ถ์ ๋ฆฌ์คํธ
+ non_videos = [name for name in ur_list['์ด๋ฆ'].values if name not in videos]
+
+ try: #๋ฏธ์ ์ถ์ ๋ฆฌ์คํธ๊ฐ ์ ๋ฝํ๋์ง ํ์ธ (ํ๊ธ์ด๋ผ ์๋ชป ๋ฝํ๋ ๊ฒฝ์ฐ ์์)
+ assert len(videos) + len(non_videos) == len(ur_list)
+
+ #์กฐ ๋ฐฐ์ ์์!
+ np.random.seed(random_seed)
+ np.random.shuffle(videos)
+ np.random.shuffle(non_videos)
+
+ video = int(len(videos)/group_num) #ํ ์กฐ ์ต์ ์ ์ถ์ ์ธ์
+ non_video = int(len(non_videos)/group_num) #ํ ์กฐ ์ต์ ๋ฏธ์ ์ถ์ ์ธ์
+ groups = {}
+
+ for i in range(group_num+1):
+ if i == group_num:
+ #1์กฐ๋ถํฐ ๋ฏธ์ ์ถ์ ๋๋จธ์ง ์ธ์ ๋ฐฐ์น
+ for j in range(len(non_videos[non_video*i:])):
+ groups[f'{j+1}์กฐ'].append(non_videos.pop())
+
+ #๋ท ์กฐ๋ถํฐ ์ ์ถ์ ๋๋จธ์ง ์ธ์ ๋ฐฐ์น
+ for j in range(len(videos[video*i:])):
+ groups[f'{group_num-j}์กฐ'].append(videos.pop())
+
+ return groups
+
+ group = videos[video*i:video*(i+1)]
+ group = group + non_videos[non_video*i:non_video*(i+1)]
+ groups[f'{i+1}์กฐ'] = group
+
+ except:
+ print(f'๋ฏธ ์ ์ถ์ ๋ฆฌ์คํธ๋ฅผ ํ์ธํ์ธ์')
+ print(f'\t* ์ด ์ธ์ ์: {len(ur_list)}๋ช
, \n\t* ๋ฏธ ์ ์ถ์ ๋ฆฌ์คํธ: {len(non_videos)}๋ช
, \n{non_videos}, \n\t* ์ ์ถ์ ๋ฆฌ์คํธ: {len(videos)}๋ช
, {videos}')
+
+ except:
+ print('์
๋ ฅํ ์ ์ถ์ ์ธ์ ์์ ์ ์ถ์ ๋ช
๋จ์ ์๋ ์๊ฐ ์ผ์นํ์ง ์์ต๋๋ค. ์ ์ถ์ ๋ช
๋จ์ ํ์ธํด ์ฃผ์ธ์')
+
+if __name__ == "__main__":
+ #๊ทธ๋ฃน ๋ง๋ค๊ธฐ
+ groups = group_maker(random_seed=1012, video=21)
+
+ #๋ช
๋จ ์ถ๋ ฅ
+ for group in groups:
+ print(groups.get(group))
+
+ #์๊ฐ์ ์ด๋ฆ์ด ๋น ์ง์์ด ๋ค์ด๊ฐ๋์ง ์ฌํ์ธ
+ j=0
+ for group in groups:
+ i = len(groups.get(group))
+ j += i
+
+ assert j == len(df) | Python | ์ด ๋ถ๋ถ๋ ํจ์ํ๋ฅผ ํ ์ ์๋๋ถ๋ถ์ด์ง ์์๊น ์ถ์ต๋๋ค ! |
@@ -0,0 +1,75 @@
+import pandas as pd
+import numpy as np
+
+#์ ์ถ์ ๋ฆฌ์คํธ(์๊ธฐ ์
๋ ฅ)
+videos = ['์กฐ์ฉ์', '์ ํํธ', '์ ์ฐ๋ฏผ', '์ฅ์งํฌ', '์์ฑ์', '์ด์น์', '์ด๋จ์ค', '์ค๋ค์', '์ค์ ๋ฆฌ๋', '์ ์์', '๋ฐฑ์กํ', '๋ฐ์๋น', '๊นํ์ฐ', '๊นํ์', '๊นํํธ', '๊นํ์ฐ', '๊น์์', '๊น์์ฐ', '๊น์ธํ', '๊ฐ์งํธ', '๊ฐ์ํ']
+#Urclass ์๊ฐ์ ํํฉ csv ๋ถ๋ฌ์ค๊ธฐ
+df = pd.read_csv('1012.csv')
+
+def group_maker(random_seed, video=len(videos), videos=videos, ur_list=df, group_num=7):
+ """
+ ์ธ์ ๋ฐฐ์น๋ ๋๋ค์ด๋ ๊ฐ ์กฐ์ ์ ์ถ์์ ์๊ฐ ์ผ์ ํ๊ฒ ๋ค์ด๊ฐ๊ฒ๋ ํ๋ก์ ํธ ์กฐ ์ง๋ ํจ์์
๋๋ค
+
+ --ํ๋ผ๋ฏธํฐ--
+ * Random seed
+ * video = ์ค์ ์ ์ถ์ ์ (int) -> ์ ์ถ์ ๋ช
๋จ์ด ์ ์
๋ ฅ๋๋ ํ์ธํ๊ธฐ ์ํจ
+ * videos = ์ ์ถ์ ๋ช
๋จ (list)
+ * ur_list = Urclass์์ exportํ ๊ธฐ์ ๋ช
๋จ (dataframe)
+ * group_num = ์กฐ ์ (int)
+ """
+ try:
+ assert len(videos) == video #์ ์ถ์ ๋ช
๋จ์ด ์ ์
๋ ฅ๋์๋์ง ํ์ธ
+
+ #๋ฏธ์ ์ถ์ ๋ฆฌ์คํธ
+ non_videos = [name for name in ur_list['์ด๋ฆ'].values if name not in videos]
+
+ try: #๋ฏธ์ ์ถ์ ๋ฆฌ์คํธ๊ฐ ์ ๋ฝํ๋์ง ํ์ธ (ํ๊ธ์ด๋ผ ์๋ชป ๋ฝํ๋ ๊ฒฝ์ฐ ์์)
+ assert len(videos) + len(non_videos) == len(ur_list)
+
+ #์กฐ ๋ฐฐ์ ์์!
+ np.random.seed(random_seed)
+ np.random.shuffle(videos)
+ np.random.shuffle(non_videos)
+
+ video = int(len(videos)/group_num) #ํ ์กฐ ์ต์ ์ ์ถ์ ์ธ์
+ non_video = int(len(non_videos)/group_num) #ํ ์กฐ ์ต์ ๋ฏธ์ ์ถ์ ์ธ์
+ groups = {}
+
+ for i in range(group_num+1):
+ if i == group_num:
+ #1์กฐ๋ถํฐ ๋ฏธ์ ์ถ์ ๋๋จธ์ง ์ธ์ ๋ฐฐ์น
+ for j in range(len(non_videos[non_video*i:])):
+ groups[f'{j+1}์กฐ'].append(non_videos.pop())
+
+ #๋ท ์กฐ๋ถํฐ ์ ์ถ์ ๋๋จธ์ง ์ธ์ ๋ฐฐ์น
+ for j in range(len(videos[video*i:])):
+ groups[f'{group_num-j}์กฐ'].append(videos.pop())
+
+ return groups
+
+ group = videos[video*i:video*(i+1)]
+ group = group + non_videos[non_video*i:non_video*(i+1)]
+ groups[f'{i+1}์กฐ'] = group
+
+ except:
+ print(f'๋ฏธ ์ ์ถ์ ๋ฆฌ์คํธ๋ฅผ ํ์ธํ์ธ์')
+ print(f'\t* ์ด ์ธ์ ์: {len(ur_list)}๋ช
, \n\t* ๋ฏธ ์ ์ถ์ ๋ฆฌ์คํธ: {len(non_videos)}๋ช
, \n{non_videos}, \n\t* ์ ์ถ์ ๋ฆฌ์คํธ: {len(videos)}๋ช
, {videos}')
+
+ except:
+ print('์
๋ ฅํ ์ ์ถ์ ์ธ์ ์์ ์ ์ถ์ ๋ช
๋จ์ ์๋ ์๊ฐ ์ผ์นํ์ง ์์ต๋๋ค. ์ ์ถ์ ๋ช
๋จ์ ํ์ธํด ์ฃผ์ธ์')
+
+if __name__ == "__main__":
+ #๊ทธ๋ฃน ๋ง๋ค๊ธฐ
+ groups = group_maker(random_seed=1012, video=21)
+
+ #๋ช
๋จ ์ถ๋ ฅ
+ for group in groups:
+ print(groups.get(group))
+
+ #์๊ฐ์ ์ด๋ฆ์ด ๋น ์ง์์ด ๋ค์ด๊ฐ๋์ง ์ฌํ์ธ
+ j=0
+ for group in groups:
+ i = len(groups.get(group))
+ j += i
+
+ assert j == len(df) | Python | ํ
์คํธ ์ผ์ด์ค๊ฐ ์๋๋ผ๋ฉด if ๋ฌธ์ ์ฐ๋๊ฒ ์ด๋จ๊น์?! |
@@ -0,0 +1,75 @@
+import pandas as pd
+import numpy as np
+
+#์ ์ถ์ ๋ฆฌ์คํธ(์๊ธฐ ์
๋ ฅ)
+videos = ['์กฐ์ฉ์', '์ ํํธ', '์ ์ฐ๋ฏผ', '์ฅ์งํฌ', '์์ฑ์', '์ด์น์', '์ด๋จ์ค', '์ค๋ค์', '์ค์ ๋ฆฌ๋', '์ ์์', '๋ฐฑ์กํ', '๋ฐ์๋น', '๊นํ์ฐ', '๊นํ์', '๊นํํธ', '๊นํ์ฐ', '๊น์์', '๊น์์ฐ', '๊น์ธํ', '๊ฐ์งํธ', '๊ฐ์ํ']
+#Urclass ์๊ฐ์ ํํฉ csv ๋ถ๋ฌ์ค๊ธฐ
+df = pd.read_csv('1012.csv')
+
+def group_maker(random_seed, video=len(videos), videos=videos, ur_list=df, group_num=7):
+ """
+ ์ธ์ ๋ฐฐ์น๋ ๋๋ค์ด๋ ๊ฐ ์กฐ์ ์ ์ถ์์ ์๊ฐ ์ผ์ ํ๊ฒ ๋ค์ด๊ฐ๊ฒ๋ ํ๋ก์ ํธ ์กฐ ์ง๋ ํจ์์
๋๋ค
+
+ --ํ๋ผ๋ฏธํฐ--
+ * Random seed
+ * video = ์ค์ ์ ์ถ์ ์ (int) -> ์ ์ถ์ ๋ช
๋จ์ด ์ ์
๋ ฅ๋๋ ํ์ธํ๊ธฐ ์ํจ
+ * videos = ์ ์ถ์ ๋ช
๋จ (list)
+ * ur_list = Urclass์์ exportํ ๊ธฐ์ ๋ช
๋จ (dataframe)
+ * group_num = ์กฐ ์ (int)
+ """
+ try:
+ assert len(videos) == video #์ ์ถ์ ๋ช
๋จ์ด ์ ์
๋ ฅ๋์๋์ง ํ์ธ
+
+ #๋ฏธ์ ์ถ์ ๋ฆฌ์คํธ
+ non_videos = [name for name in ur_list['์ด๋ฆ'].values if name not in videos]
+
+ try: #๋ฏธ์ ์ถ์ ๋ฆฌ์คํธ๊ฐ ์ ๋ฝํ๋์ง ํ์ธ (ํ๊ธ์ด๋ผ ์๋ชป ๋ฝํ๋ ๊ฒฝ์ฐ ์์)
+ assert len(videos) + len(non_videos) == len(ur_list)
+
+ #์กฐ ๋ฐฐ์ ์์!
+ np.random.seed(random_seed)
+ np.random.shuffle(videos)
+ np.random.shuffle(non_videos)
+
+ video = int(len(videos)/group_num) #ํ ์กฐ ์ต์ ์ ์ถ์ ์ธ์
+ non_video = int(len(non_videos)/group_num) #ํ ์กฐ ์ต์ ๋ฏธ์ ์ถ์ ์ธ์
+ groups = {}
+
+ for i in range(group_num+1):
+ if i == group_num:
+ #1์กฐ๋ถํฐ ๋ฏธ์ ์ถ์ ๋๋จธ์ง ์ธ์ ๋ฐฐ์น
+ for j in range(len(non_videos[non_video*i:])):
+ groups[f'{j+1}์กฐ'].append(non_videos.pop())
+
+ #๋ท ์กฐ๋ถํฐ ์ ์ถ์ ๋๋จธ์ง ์ธ์ ๋ฐฐ์น
+ for j in range(len(videos[video*i:])):
+ groups[f'{group_num-j}์กฐ'].append(videos.pop())
+
+ return groups
+
+ group = videos[video*i:video*(i+1)]
+ group = group + non_videos[non_video*i:non_video*(i+1)]
+ groups[f'{i+1}์กฐ'] = group
+
+ except:
+ print(f'๋ฏธ ์ ์ถ์ ๋ฆฌ์คํธ๋ฅผ ํ์ธํ์ธ์')
+ print(f'\t* ์ด ์ธ์ ์: {len(ur_list)}๋ช
, \n\t* ๋ฏธ ์ ์ถ์ ๋ฆฌ์คํธ: {len(non_videos)}๋ช
, \n{non_videos}, \n\t* ์ ์ถ์ ๋ฆฌ์คํธ: {len(videos)}๋ช
, {videos}')
+
+ except:
+ print('์
๋ ฅํ ์ ์ถ์ ์ธ์ ์์ ์ ์ถ์ ๋ช
๋จ์ ์๋ ์๊ฐ ์ผ์นํ์ง ์์ต๋๋ค. ์ ์ถ์ ๋ช
๋จ์ ํ์ธํด ์ฃผ์ธ์')
+
+if __name__ == "__main__":
+ #๊ทธ๋ฃน ๋ง๋ค๊ธฐ
+ groups = group_maker(random_seed=1012, video=21)
+
+ #๋ช
๋จ ์ถ๋ ฅ
+ for group in groups:
+ print(groups.get(group))
+
+ #์๊ฐ์ ์ด๋ฆ์ด ๋น ์ง์์ด ๋ค์ด๊ฐ๋์ง ์ฌํ์ธ
+ j=0
+ for group in groups:
+ i = len(groups.get(group))
+ j += i
+
+ assert j == len(df) | Python | ํ
์คํธ ์ผ์ด์ค๊ฐ ์๋๋ผ๋ฉด if ๋ฌธ์ ์ฐ๋๊ฒ ์ด๋จ๊น์?! |
@@ -0,0 +1,75 @@
+import pandas as pd
+import numpy as np
+
+#์ ์ถ์ ๋ฆฌ์คํธ(์๊ธฐ ์
๋ ฅ)
+videos = ['์กฐ์ฉ์', '์ ํํธ', '์ ์ฐ๋ฏผ', '์ฅ์งํฌ', '์์ฑ์', '์ด์น์', '์ด๋จ์ค', '์ค๋ค์', '์ค์ ๋ฆฌ๋', '์ ์์', '๋ฐฑ์กํ', '๋ฐ์๋น', '๊นํ์ฐ', '๊นํ์', '๊นํํธ', '๊นํ์ฐ', '๊น์์', '๊น์์ฐ', '๊น์ธํ', '๊ฐ์งํธ', '๊ฐ์ํ']
+#Urclass ์๊ฐ์ ํํฉ csv ๋ถ๋ฌ์ค๊ธฐ
+df = pd.read_csv('1012.csv')
+
+def group_maker(random_seed, video=len(videos), videos=videos, ur_list=df, group_num=7):
+ """
+ ์ธ์ ๋ฐฐ์น๋ ๋๋ค์ด๋ ๊ฐ ์กฐ์ ์ ์ถ์์ ์๊ฐ ์ผ์ ํ๊ฒ ๋ค์ด๊ฐ๊ฒ๋ ํ๋ก์ ํธ ์กฐ ์ง๋ ํจ์์
๋๋ค
+
+ --ํ๋ผ๋ฏธํฐ--
+ * Random seed
+ * video = ์ค์ ์ ์ถ์ ์ (int) -> ์ ์ถ์ ๋ช
๋จ์ด ์ ์
๋ ฅ๋๋ ํ์ธํ๊ธฐ ์ํจ
+ * videos = ์ ์ถ์ ๋ช
๋จ (list)
+ * ur_list = Urclass์์ exportํ ๊ธฐ์ ๋ช
๋จ (dataframe)
+ * group_num = ์กฐ ์ (int)
+ """
+ try:
+ assert len(videos) == video #์ ์ถ์ ๋ช
๋จ์ด ์ ์
๋ ฅ๋์๋์ง ํ์ธ
+
+ #๋ฏธ์ ์ถ์ ๋ฆฌ์คํธ
+ non_videos = [name for name in ur_list['์ด๋ฆ'].values if name not in videos]
+
+ try: #๋ฏธ์ ์ถ์ ๋ฆฌ์คํธ๊ฐ ์ ๋ฝํ๋์ง ํ์ธ (ํ๊ธ์ด๋ผ ์๋ชป ๋ฝํ๋ ๊ฒฝ์ฐ ์์)
+ assert len(videos) + len(non_videos) == len(ur_list)
+
+ #์กฐ ๋ฐฐ์ ์์!
+ np.random.seed(random_seed)
+ np.random.shuffle(videos)
+ np.random.shuffle(non_videos)
+
+ video = int(len(videos)/group_num) #ํ ์กฐ ์ต์ ์ ์ถ์ ์ธ์
+ non_video = int(len(non_videos)/group_num) #ํ ์กฐ ์ต์ ๋ฏธ์ ์ถ์ ์ธ์
+ groups = {}
+
+ for i in range(group_num+1):
+ if i == group_num:
+ #1์กฐ๋ถํฐ ๋ฏธ์ ์ถ์ ๋๋จธ์ง ์ธ์ ๋ฐฐ์น
+ for j in range(len(non_videos[non_video*i:])):
+ groups[f'{j+1}์กฐ'].append(non_videos.pop())
+
+ #๋ท ์กฐ๋ถํฐ ์ ์ถ์ ๋๋จธ์ง ์ธ์ ๋ฐฐ์น
+ for j in range(len(videos[video*i:])):
+ groups[f'{group_num-j}์กฐ'].append(videos.pop())
+
+ return groups
+
+ group = videos[video*i:video*(i+1)]
+ group = group + non_videos[non_video*i:non_video*(i+1)]
+ groups[f'{i+1}์กฐ'] = group
+
+ except:
+ print(f'๋ฏธ ์ ์ถ์ ๋ฆฌ์คํธ๋ฅผ ํ์ธํ์ธ์')
+ print(f'\t* ์ด ์ธ์ ์: {len(ur_list)}๋ช
, \n\t* ๋ฏธ ์ ์ถ์ ๋ฆฌ์คํธ: {len(non_videos)}๋ช
, \n{non_videos}, \n\t* ์ ์ถ์ ๋ฆฌ์คํธ: {len(videos)}๋ช
, {videos}')
+
+ except:
+ print('์
๋ ฅํ ์ ์ถ์ ์ธ์ ์์ ์ ์ถ์ ๋ช
๋จ์ ์๋ ์๊ฐ ์ผ์นํ์ง ์์ต๋๋ค. ์ ์ถ์ ๋ช
๋จ์ ํ์ธํด ์ฃผ์ธ์')
+
+if __name__ == "__main__":
+ #๊ทธ๋ฃน ๋ง๋ค๊ธฐ
+ groups = group_maker(random_seed=1012, video=21)
+
+ #๋ช
๋จ ์ถ๋ ฅ
+ for group in groups:
+ print(groups.get(group))
+
+ #์๊ฐ์ ์ด๋ฆ์ด ๋น ์ง์์ด ๋ค์ด๊ฐ๋์ง ์ฌํ์ธ
+ j=0
+ for group in groups:
+ i = len(groups.get(group))
+ j += i
+
+ assert j == len(df) | Python | try except๋ฅผ ์ฌ์ฉํ๋ ๊ฒ๋ณด๋ค ํ์ธ์ฉ์ด๋ผ๋ฉด assert ๋ฌธ์ ํ์ฉํ์
๋ ์ข์๋ฏํฉ๋๋ค. |
@@ -0,0 +1,75 @@
+import pandas as pd
+import numpy as np
+
+#์ ์ถ์ ๋ฆฌ์คํธ(์๊ธฐ ์
๋ ฅ)
+videos = ['์กฐ์ฉ์', '์ ํํธ', '์ ์ฐ๋ฏผ', '์ฅ์งํฌ', '์์ฑ์', '์ด์น์', '์ด๋จ์ค', '์ค๋ค์', '์ค์ ๋ฆฌ๋', '์ ์์', '๋ฐฑ์กํ', '๋ฐ์๋น', '๊นํ์ฐ', '๊นํ์', '๊นํํธ', '๊นํ์ฐ', '๊น์์', '๊น์์ฐ', '๊น์ธํ', '๊ฐ์งํธ', '๊ฐ์ํ']
+#Urclass ์๊ฐ์ ํํฉ csv ๋ถ๋ฌ์ค๊ธฐ
+df = pd.read_csv('1012.csv')
+
+def group_maker(random_seed, video=len(videos), videos=videos, ur_list=df, group_num=7):
+ """
+ ์ธ์ ๋ฐฐ์น๋ ๋๋ค์ด๋ ๊ฐ ์กฐ์ ์ ์ถ์์ ์๊ฐ ์ผ์ ํ๊ฒ ๋ค์ด๊ฐ๊ฒ๋ ํ๋ก์ ํธ ์กฐ ์ง๋ ํจ์์
๋๋ค
+
+ --ํ๋ผ๋ฏธํฐ--
+ * Random seed
+ * video = ์ค์ ์ ์ถ์ ์ (int) -> ์ ์ถ์ ๋ช
๋จ์ด ์ ์
๋ ฅ๋๋ ํ์ธํ๊ธฐ ์ํจ
+ * videos = ์ ์ถ์ ๋ช
๋จ (list)
+ * ur_list = Urclass์์ exportํ ๊ธฐ์ ๋ช
๋จ (dataframe)
+ * group_num = ์กฐ ์ (int)
+ """
+ try:
+ assert len(videos) == video #์ ์ถ์ ๋ช
๋จ์ด ์ ์
๋ ฅ๋์๋์ง ํ์ธ
+
+ #๋ฏธ์ ์ถ์ ๋ฆฌ์คํธ
+ non_videos = [name for name in ur_list['์ด๋ฆ'].values if name not in videos]
+
+ try: #๋ฏธ์ ์ถ์ ๋ฆฌ์คํธ๊ฐ ์ ๋ฝํ๋์ง ํ์ธ (ํ๊ธ์ด๋ผ ์๋ชป ๋ฝํ๋ ๊ฒฝ์ฐ ์์)
+ assert len(videos) + len(non_videos) == len(ur_list)
+
+ #์กฐ ๋ฐฐ์ ์์!
+ np.random.seed(random_seed)
+ np.random.shuffle(videos)
+ np.random.shuffle(non_videos)
+
+ video = int(len(videos)/group_num) #ํ ์กฐ ์ต์ ์ ์ถ์ ์ธ์
+ non_video = int(len(non_videos)/group_num) #ํ ์กฐ ์ต์ ๋ฏธ์ ์ถ์ ์ธ์
+ groups = {}
+
+ for i in range(group_num+1):
+ if i == group_num:
+ #1์กฐ๋ถํฐ ๋ฏธ์ ์ถ์ ๋๋จธ์ง ์ธ์ ๋ฐฐ์น
+ for j in range(len(non_videos[non_video*i:])):
+ groups[f'{j+1}์กฐ'].append(non_videos.pop())
+
+ #๋ท ์กฐ๋ถํฐ ์ ์ถ์ ๋๋จธ์ง ์ธ์ ๋ฐฐ์น
+ for j in range(len(videos[video*i:])):
+ groups[f'{group_num-j}์กฐ'].append(videos.pop())
+
+ return groups
+
+ group = videos[video*i:video*(i+1)]
+ group = group + non_videos[non_video*i:non_video*(i+1)]
+ groups[f'{i+1}์กฐ'] = group
+
+ except:
+ print(f'๋ฏธ ์ ์ถ์ ๋ฆฌ์คํธ๋ฅผ ํ์ธํ์ธ์')
+ print(f'\t* ์ด ์ธ์ ์: {len(ur_list)}๋ช
, \n\t* ๋ฏธ ์ ์ถ์ ๋ฆฌ์คํธ: {len(non_videos)}๋ช
, \n{non_videos}, \n\t* ์ ์ถ์ ๋ฆฌ์คํธ: {len(videos)}๋ช
, {videos}')
+
+ except:
+ print('์
๋ ฅํ ์ ์ถ์ ์ธ์ ์์ ์ ์ถ์ ๋ช
๋จ์ ์๋ ์๊ฐ ์ผ์นํ์ง ์์ต๋๋ค. ์ ์ถ์ ๋ช
๋จ์ ํ์ธํด ์ฃผ์ธ์')
+
+if __name__ == "__main__":
+ #๊ทธ๋ฃน ๋ง๋ค๊ธฐ
+ groups = group_maker(random_seed=1012, video=21)
+
+ #๋ช
๋จ ์ถ๋ ฅ
+ for group in groups:
+ print(groups.get(group))
+
+ #์๊ฐ์ ์ด๋ฆ์ด ๋น ์ง์์ด ๋ค์ด๊ฐ๋์ง ์ฌํ์ธ
+ j=0
+ for group in groups:
+ i = len(groups.get(group))
+ j += i
+
+ assert j == len(df) | Python | `def group_maker(random_seed, video=len(videos), videos=videos, ur_list=df, group_num=7): `
# ํจ์๊ฐ ์ ์ธ๋๋ ๋ถ๋ถ์๋ `video=len(videos)`์ฒ๋ผ ๋ด์ฅํจ์๊ฐ ์๋ ๊ฒ์ด ์ข์ต๋๋ค.
# ์ด๋ฌํ ๊ฒฝ์ฐ ํจ์ ๋ด๋ถ์ `video` ๋ณ์๊ฐ์ ๋ฐ์์ค๋ ๊ณ์ฐ์์ ๋ง๋๋ ๊ฒ์ด ์ข์ต๋๋ค.
# ์๋ํ๋ฉด ํจ์์ ์ธ๋ถ์ ๊ณ์ฐ์์ด๋ ๋ด์ฅํจ์๊ฐ ํธ์ถ๋๋ฉด `project_group.py์ฝ๋`๊ฐ ํธ์ถ๋๊ฑฐ๋ `group_makerํจ์`๊ฐ ํธ์ถ๋ ๋๋ง๋ค ์ถ๊ฐ์ ์ผ๋ก ๋ฉ๋ชจ๋ฆฌ๊ฐ ์๋น๋ ์ ์์ต๋๋ค. |
@@ -0,0 +1,75 @@
+import pandas as pd
+import numpy as np
+
+#์ ์ถ์ ๋ฆฌ์คํธ(์๊ธฐ ์
๋ ฅ)
+videos = ['์กฐ์ฉ์', '์ ํํธ', '์ ์ฐ๋ฏผ', '์ฅ์งํฌ', '์์ฑ์', '์ด์น์', '์ด๋จ์ค', '์ค๋ค์', '์ค์ ๋ฆฌ๋', '์ ์์', '๋ฐฑ์กํ', '๋ฐ์๋น', '๊นํ์ฐ', '๊นํ์', '๊นํํธ', '๊นํ์ฐ', '๊น์์', '๊น์์ฐ', '๊น์ธํ', '๊ฐ์งํธ', '๊ฐ์ํ']
+#Urclass ์๊ฐ์ ํํฉ csv ๋ถ๋ฌ์ค๊ธฐ
+df = pd.read_csv('1012.csv')
+
+def group_maker(random_seed, video=len(videos), videos=videos, ur_list=df, group_num=7):
+ """
+ ์ธ์ ๋ฐฐ์น๋ ๋๋ค์ด๋ ๊ฐ ์กฐ์ ์ ์ถ์์ ์๊ฐ ์ผ์ ํ๊ฒ ๋ค์ด๊ฐ๊ฒ๋ ํ๋ก์ ํธ ์กฐ ์ง๋ ํจ์์
๋๋ค
+
+ --ํ๋ผ๋ฏธํฐ--
+ * Random seed
+ * video = ์ค์ ์ ์ถ์ ์ (int) -> ์ ์ถ์ ๋ช
๋จ์ด ์ ์
๋ ฅ๋๋ ํ์ธํ๊ธฐ ์ํจ
+ * videos = ์ ์ถ์ ๋ช
๋จ (list)
+ * ur_list = Urclass์์ exportํ ๊ธฐ์ ๋ช
๋จ (dataframe)
+ * group_num = ์กฐ ์ (int)
+ """
+ try:
+ assert len(videos) == video #์ ์ถ์ ๋ช
๋จ์ด ์ ์
๋ ฅ๋์๋์ง ํ์ธ
+
+ #๋ฏธ์ ์ถ์ ๋ฆฌ์คํธ
+ non_videos = [name for name in ur_list['์ด๋ฆ'].values if name not in videos]
+
+ try: #๋ฏธ์ ์ถ์ ๋ฆฌ์คํธ๊ฐ ์ ๋ฝํ๋์ง ํ์ธ (ํ๊ธ์ด๋ผ ์๋ชป ๋ฝํ๋ ๊ฒฝ์ฐ ์์)
+ assert len(videos) + len(non_videos) == len(ur_list)
+
+ #์กฐ ๋ฐฐ์ ์์!
+ np.random.seed(random_seed)
+ np.random.shuffle(videos)
+ np.random.shuffle(non_videos)
+
+ video = int(len(videos)/group_num) #ํ ์กฐ ์ต์ ์ ์ถ์ ์ธ์
+ non_video = int(len(non_videos)/group_num) #ํ ์กฐ ์ต์ ๋ฏธ์ ์ถ์ ์ธ์
+ groups = {}
+
+ for i in range(group_num+1):
+ if i == group_num:
+ #1์กฐ๋ถํฐ ๋ฏธ์ ์ถ์ ๋๋จธ์ง ์ธ์ ๋ฐฐ์น
+ for j in range(len(non_videos[non_video*i:])):
+ groups[f'{j+1}์กฐ'].append(non_videos.pop())
+
+ #๋ท ์กฐ๋ถํฐ ์ ์ถ์ ๋๋จธ์ง ์ธ์ ๋ฐฐ์น
+ for j in range(len(videos[video*i:])):
+ groups[f'{group_num-j}์กฐ'].append(videos.pop())
+
+ return groups
+
+ group = videos[video*i:video*(i+1)]
+ group = group + non_videos[non_video*i:non_video*(i+1)]
+ groups[f'{i+1}์กฐ'] = group
+
+ except:
+ print(f'๋ฏธ ์ ์ถ์ ๋ฆฌ์คํธ๋ฅผ ํ์ธํ์ธ์')
+ print(f'\t* ์ด ์ธ์ ์: {len(ur_list)}๋ช
, \n\t* ๋ฏธ ์ ์ถ์ ๋ฆฌ์คํธ: {len(non_videos)}๋ช
, \n{non_videos}, \n\t* ์ ์ถ์ ๋ฆฌ์คํธ: {len(videos)}๋ช
, {videos}')
+
+ except:
+ print('์
๋ ฅํ ์ ์ถ์ ์ธ์ ์์ ์ ์ถ์ ๋ช
๋จ์ ์๋ ์๊ฐ ์ผ์นํ์ง ์์ต๋๋ค. ์ ์ถ์ ๋ช
๋จ์ ํ์ธํด ์ฃผ์ธ์')
+
+if __name__ == "__main__":
+ #๊ทธ๋ฃน ๋ง๋ค๊ธฐ
+ groups = group_maker(random_seed=1012, video=21)
+
+ #๋ช
๋จ ์ถ๋ ฅ
+ for group in groups:
+ print(groups.get(group))
+
+ #์๊ฐ์ ์ด๋ฆ์ด ๋น ์ง์์ด ๋ค์ด๊ฐ๋์ง ์ฌํ์ธ
+ j=0
+ for group in groups:
+ i = len(groups.get(group))
+ j += i
+
+ assert j == len(df) | Python | โ๏ธ ์์ `ํ
์คํธ ์ผ์ด์ค๊ฐ ์๋๋ผ๋ฉด if ๋ฌธ์ ์ฐ๋๊ฒ ์ด๋จ๊น์?!` ๋ผ๊ณ ๋จ๊ฒผ๋๋ฐ, ๋ ์ฐพ์๋ณด๋ ์ด๋ค ์ํฉ์ ๊ฐ์ ํ๊ณ , ๊ทธ ์ํฉ์ด `AssertError` ๋ก ๊ด๋ฆฌ๋์ด์ผํ๋ค๋ฉด if ๋ณด๋ค assert ๋ฅผ ์ฌ์ฉํ๋๊ฒ ๋ ๊ฐ๊ฒฐํ๊ณ , ๋ช
ํํ๊ฒ ํํ๋ ์ ์๊ฒ ๋ค์ ใ
0ใ
์ ์ฝ๋ฉํธ๋ ๋ฌด์ํ์
๋ ์ข์ต๋๋ค |
@@ -0,0 +1,11 @@
+import styled from 'styled-components';
+
+export const HeaderWrapper = styled.header`
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ width: 100%;
+ height: ${({ theme }) => theme.boxHeight};
+ padding: 0px 24px;
+ background: ${({ theme }) => theme.color.primary.main};
+`; | Unknown | ์ด ๊ตฌํ๋ ์ ๋ง ์ข์๋ฐ์~
๋ง์ด ๋ด๋ ค๊ฐ ์ํ์์ ํค๋๋ฅผ ๋ค์ ๋ณด๋ ค๋ฉด ์๋ก ๋ง์ด ์ฌ๋ผ๊ฐ์ผํด์ ์ด๋ ค์ธ ๊ฒ ๊ฐ์์
๋ฌดํ ํ์ด์ง ํน์ฑ์ position:sticky ์ต์
์ ํ์ฉํ์ฌ
๋ค๋น๊ฒ์ด์
๋ฐ๊ฐ ๋ฌ๋ค๋ฉด UX๊ฒฝํ์ด ๋ ์ข์์ง ๊ฑฐ๊ฐ์์. |
@@ -0,0 +1,146 @@
+import { CartStoreState, User } from 'types/index';
+import { useDispatch, useSelector } from 'react-redux';
+
+import Link from 'components/@shared/Link';
+import Logo from 'components/Logo/Logo';
+import PATH from 'constants/path';
+import RightMenu from './RightMenu';
+import { isLogin } from 'utils/auth';
+import styled from 'styled-components';
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
+import { userActions } from 'redux/actions';
+
+function Header() {
+ const navigate = useNavigate();
+ const dispatch = useDispatch();
+
+ const cart = useSelector(
+ (state: { cart: CartStoreState }) => state.cart.cart,
+ );
+ const userName = useSelector((state: { user: User }) => state.user.username);
+
+ const [showUserToggle, setShowUserToggle] = useState(false);
+
+ const onClickLogoutButton = () => {
+ dispatch(userActions.resetUser());
+
+ localStorage.removeItem('accessToken');
+ sessionStorage.removeItem('accessToken');
+
+ navigate(PATH.BASE);
+ };
+
+ const onClickEditUserInfoButton = () => {
+ navigate(PATH.EDIT_USER_INFO);
+ };
+
+ return (
+ <>
+ <StyledHeader>
+ <Link to={PATH.BASE}>
+ <Logo />
+ </Link>
+ <RightMenu>
+ <Link to={PATH.CART}>
+ ์ฅ๋ฐ๊ตฌ๋
+ <Badge>{cart.length}</Badge>
+ </Link>
+ <Link to={PATH.BASE}>์ฃผ๋ฌธ๋ชฉ๋ก</Link>
+ </RightMenu>
+ </StyledHeader>
+ <StyledSubHeader>
+ <RightMenu gap="30px">
+ {!isLogin() ? (
+ <>
+ <Link to={PATH.LOGIN}>๋ก๊ทธ์ธ</Link>
+ <Link to={PATH.SIGNUP}>ํ์๊ฐ์
</Link>
+ </>
+ ) : (
+ <>
+ {userName}๋ ํ์ํฉ๋๋ค
+ <StyledControlUserButton onClick={onClickLogoutButton}>
+ ๋ก๊ทธ์์
+ </StyledControlUserButton>
+ <StyledControlUserButton onClick={onClickEditUserInfoButton}>
+ ํ์ ์ ๋ณด ์์
+ </StyledControlUserButton>
+ </>
+ )}
+ </RightMenu>
+ </StyledSubHeader>
+ </>
+ );
+}
+
+const StyledHeader = styled.div`
+ display: flex;
+ flex-direction: row;
+ justify-content: space-between;
+ align-items: center;
+ position: sticky;
+
+ font-size: 20px;
+ height: 60px;
+ padding: 0 10%;
+ top: 0px;
+ z-index: ${({ theme: { zPriorities } }) => zPriorities.overEverything};
+
+ background: ${({ theme: { colors } }) => colors.redPink};
+ color: ${({ theme: { colors } }) => colors.white};
+
+ ${RightMenu} {
+ text-shadow: -0.5px 0 ${({ theme: { colors } }) => colors.gray},
+ 0 0.5px ${({ theme: { colors } }) => colors.gray},
+ 0.5px 0 ${({ theme: { colors } }) => colors.gray},
+ 0 -0.5px ${({ theme: { colors } }) => colors.gray};
+ }
+`;
+
+const Badge = styled.div`
+ display: inline-block;
+ position: absolute;
+ top: 10px;
+ text-align: center;
+
+ width: 15px;
+ height: 15px;
+ border: 0.5px solid ${({ theme: { colors } }) => colors.white};
+ border-radius: 50%;
+
+ background: ${({ theme: { colors } }) => colors.pink};
+ color: ${({ theme: { colors } }) => colors.black};
+
+ font-size: 14px;
+ font-weight: normal !important;
+`;
+
+const StyledSubHeader = styled.div`
+ display: flex;
+ flex-direction: row;
+ justify-content: flex-end;
+ align-items: center;
+ position: sticky;
+
+ font-size: 16px;
+ height: 24px;
+ padding: 0 10%;
+ top: 60px;
+ z-index: ${({ theme: { zPriorities } }) => zPriorities.overEverything};
+
+ background: ${({ theme: { colors } }) => colors.white};
+ color: ${({ theme: { colors } }) => colors.black};
+`;
+
+const StyledControlUserButton = styled.button`
+ border-radius: 12px;
+ padding: 0 12px;
+
+ background-color: ${({ theme: { colors } }) => colors.pink};
+ color: ${({ theme: { colors } }) => colors.white};
+
+ font-weight: 800;
+ font-size: 14px;
+`;
+
+export default Header; | Unknown | state.cart.cart๋ ์ด์ง ์์ฌ์ด ๋ค์ด๋ฐ์ธ๊ฒ ๊ฐ์์!
items ์ ๋๋ฉด ๊ด์ฐฎ์ ๋ค์ด๋ฐ์ด์ง ์์๊น ์๊ฐํด๋ด
๋๋ค ๐ |
@@ -0,0 +1,146 @@
+import { CartStoreState, User } from 'types/index';
+import { useDispatch, useSelector } from 'react-redux';
+
+import Link from 'components/@shared/Link';
+import Logo from 'components/Logo/Logo';
+import PATH from 'constants/path';
+import RightMenu from './RightMenu';
+import { isLogin } from 'utils/auth';
+import styled from 'styled-components';
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
+import { userActions } from 'redux/actions';
+
+function Header() {
+ const navigate = useNavigate();
+ const dispatch = useDispatch();
+
+ const cart = useSelector(
+ (state: { cart: CartStoreState }) => state.cart.cart,
+ );
+ const userName = useSelector((state: { user: User }) => state.user.username);
+
+ const [showUserToggle, setShowUserToggle] = useState(false);
+
+ const onClickLogoutButton = () => {
+ dispatch(userActions.resetUser());
+
+ localStorage.removeItem('accessToken');
+ sessionStorage.removeItem('accessToken');
+
+ navigate(PATH.BASE);
+ };
+
+ const onClickEditUserInfoButton = () => {
+ navigate(PATH.EDIT_USER_INFO);
+ };
+
+ return (
+ <>
+ <StyledHeader>
+ <Link to={PATH.BASE}>
+ <Logo />
+ </Link>
+ <RightMenu>
+ <Link to={PATH.CART}>
+ ์ฅ๋ฐ๊ตฌ๋
+ <Badge>{cart.length}</Badge>
+ </Link>
+ <Link to={PATH.BASE}>์ฃผ๋ฌธ๋ชฉ๋ก</Link>
+ </RightMenu>
+ </StyledHeader>
+ <StyledSubHeader>
+ <RightMenu gap="30px">
+ {!isLogin() ? (
+ <>
+ <Link to={PATH.LOGIN}>๋ก๊ทธ์ธ</Link>
+ <Link to={PATH.SIGNUP}>ํ์๊ฐ์
</Link>
+ </>
+ ) : (
+ <>
+ {userName}๋ ํ์ํฉ๋๋ค
+ <StyledControlUserButton onClick={onClickLogoutButton}>
+ ๋ก๊ทธ์์
+ </StyledControlUserButton>
+ <StyledControlUserButton onClick={onClickEditUserInfoButton}>
+ ํ์ ์ ๋ณด ์์
+ </StyledControlUserButton>
+ </>
+ )}
+ </RightMenu>
+ </StyledSubHeader>
+ </>
+ );
+}
+
+const StyledHeader = styled.div`
+ display: flex;
+ flex-direction: row;
+ justify-content: space-between;
+ align-items: center;
+ position: sticky;
+
+ font-size: 20px;
+ height: 60px;
+ padding: 0 10%;
+ top: 0px;
+ z-index: ${({ theme: { zPriorities } }) => zPriorities.overEverything};
+
+ background: ${({ theme: { colors } }) => colors.redPink};
+ color: ${({ theme: { colors } }) => colors.white};
+
+ ${RightMenu} {
+ text-shadow: -0.5px 0 ${({ theme: { colors } }) => colors.gray},
+ 0 0.5px ${({ theme: { colors } }) => colors.gray},
+ 0.5px 0 ${({ theme: { colors } }) => colors.gray},
+ 0 -0.5px ${({ theme: { colors } }) => colors.gray};
+ }
+`;
+
+const Badge = styled.div`
+ display: inline-block;
+ position: absolute;
+ top: 10px;
+ text-align: center;
+
+ width: 15px;
+ height: 15px;
+ border: 0.5px solid ${({ theme: { colors } }) => colors.white};
+ border-radius: 50%;
+
+ background: ${({ theme: { colors } }) => colors.pink};
+ color: ${({ theme: { colors } }) => colors.black};
+
+ font-size: 14px;
+ font-weight: normal !important;
+`;
+
+const StyledSubHeader = styled.div`
+ display: flex;
+ flex-direction: row;
+ justify-content: flex-end;
+ align-items: center;
+ position: sticky;
+
+ font-size: 16px;
+ height: 24px;
+ padding: 0 10%;
+ top: 60px;
+ z-index: ${({ theme: { zPriorities } }) => zPriorities.overEverything};
+
+ background: ${({ theme: { colors } }) => colors.white};
+ color: ${({ theme: { colors } }) => colors.black};
+`;
+
+const StyledControlUserButton = styled.button`
+ border-radius: 12px;
+ padding: 0 12px;
+
+ background-color: ${({ theme: { colors } }) => colors.pink};
+ color: ${({ theme: { colors } }) => colors.white};
+
+ font-weight: 800;
+ font-size: 14px;
+`;
+
+export default Header; | Unknown | showUserToggle์ ์ด๋์์ ์ฌ์ฉ๋๊ณ ์๋ ๋ณ์์ธ๊ฐ์?
์ฐพ์๋ณด๊ณ ์๋๋ฐ ์ ์ ๋ณด์ด๋ค์ ๐ฅ |
@@ -0,0 +1,146 @@
+import { CartStoreState, User } from 'types/index';
+import { useDispatch, useSelector } from 'react-redux';
+
+import Link from 'components/@shared/Link';
+import Logo from 'components/Logo/Logo';
+import PATH from 'constants/path';
+import RightMenu from './RightMenu';
+import { isLogin } from 'utils/auth';
+import styled from 'styled-components';
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
+import { userActions } from 'redux/actions';
+
+function Header() {
+ const navigate = useNavigate();
+ const dispatch = useDispatch();
+
+ const cart = useSelector(
+ (state: { cart: CartStoreState }) => state.cart.cart,
+ );
+ const userName = useSelector((state: { user: User }) => state.user.username);
+
+ const [showUserToggle, setShowUserToggle] = useState(false);
+
+ const onClickLogoutButton = () => {
+ dispatch(userActions.resetUser());
+
+ localStorage.removeItem('accessToken');
+ sessionStorage.removeItem('accessToken');
+
+ navigate(PATH.BASE);
+ };
+
+ const onClickEditUserInfoButton = () => {
+ navigate(PATH.EDIT_USER_INFO);
+ };
+
+ return (
+ <>
+ <StyledHeader>
+ <Link to={PATH.BASE}>
+ <Logo />
+ </Link>
+ <RightMenu>
+ <Link to={PATH.CART}>
+ ์ฅ๋ฐ๊ตฌ๋
+ <Badge>{cart.length}</Badge>
+ </Link>
+ <Link to={PATH.BASE}>์ฃผ๋ฌธ๋ชฉ๋ก</Link>
+ </RightMenu>
+ </StyledHeader>
+ <StyledSubHeader>
+ <RightMenu gap="30px">
+ {!isLogin() ? (
+ <>
+ <Link to={PATH.LOGIN}>๋ก๊ทธ์ธ</Link>
+ <Link to={PATH.SIGNUP}>ํ์๊ฐ์
</Link>
+ </>
+ ) : (
+ <>
+ {userName}๋ ํ์ํฉ๋๋ค
+ <StyledControlUserButton onClick={onClickLogoutButton}>
+ ๋ก๊ทธ์์
+ </StyledControlUserButton>
+ <StyledControlUserButton onClick={onClickEditUserInfoButton}>
+ ํ์ ์ ๋ณด ์์
+ </StyledControlUserButton>
+ </>
+ )}
+ </RightMenu>
+ </StyledSubHeader>
+ </>
+ );
+}
+
+const StyledHeader = styled.div`
+ display: flex;
+ flex-direction: row;
+ justify-content: space-between;
+ align-items: center;
+ position: sticky;
+
+ font-size: 20px;
+ height: 60px;
+ padding: 0 10%;
+ top: 0px;
+ z-index: ${({ theme: { zPriorities } }) => zPriorities.overEverything};
+
+ background: ${({ theme: { colors } }) => colors.redPink};
+ color: ${({ theme: { colors } }) => colors.white};
+
+ ${RightMenu} {
+ text-shadow: -0.5px 0 ${({ theme: { colors } }) => colors.gray},
+ 0 0.5px ${({ theme: { colors } }) => colors.gray},
+ 0.5px 0 ${({ theme: { colors } }) => colors.gray},
+ 0 -0.5px ${({ theme: { colors } }) => colors.gray};
+ }
+`;
+
+const Badge = styled.div`
+ display: inline-block;
+ position: absolute;
+ top: 10px;
+ text-align: center;
+
+ width: 15px;
+ height: 15px;
+ border: 0.5px solid ${({ theme: { colors } }) => colors.white};
+ border-radius: 50%;
+
+ background: ${({ theme: { colors } }) => colors.pink};
+ color: ${({ theme: { colors } }) => colors.black};
+
+ font-size: 14px;
+ font-weight: normal !important;
+`;
+
+const StyledSubHeader = styled.div`
+ display: flex;
+ flex-direction: row;
+ justify-content: flex-end;
+ align-items: center;
+ position: sticky;
+
+ font-size: 16px;
+ height: 24px;
+ padding: 0 10%;
+ top: 60px;
+ z-index: ${({ theme: { zPriorities } }) => zPriorities.overEverything};
+
+ background: ${({ theme: { colors } }) => colors.white};
+ color: ${({ theme: { colors } }) => colors.black};
+`;
+
+const StyledControlUserButton = styled.button`
+ border-radius: 12px;
+ padding: 0 12px;
+
+ background-color: ${({ theme: { colors } }) => colors.pink};
+ color: ${({ theme: { colors } }) => colors.white};
+
+ font-weight: 800;
+ font-size: 14px;
+`;
+
+export default Header; | Unknown | localStorage์ sessionStorage๋ฅผ ๋ชจ๋ ์ฌ์ฉํ ์ด์ ๊ฐ ์์๊น์? |
@@ -0,0 +1,143 @@
+import CheckBox from 'components/@shared/CheckBox';
+import Link from 'components/@shared/Link';
+import PATH from 'constants/path';
+import { USER_MESSAGE } from 'constants/message';
+import authAPI from 'apis/auth';
+import { createInputValueGetter } from 'utils/dom';
+import styled from 'styled-components';
+import { useDispatch } from 'react-redux';
+import { useNavigate } from 'react-router-dom';
+import { useState } from 'react';
+import { userActions } from 'redux/actions';
+
+function LoginForm() {
+ const dispatch = useDispatch();
+ const navigate = useNavigate();
+
+ const [checked, setChecked] = useState(false);
+
+ const toggleChecked = (
+ e: React.MouseEvent<HTMLElement> | React.ChangeEvent<HTMLElement>,
+ ) => {
+ e.preventDefault();
+
+ setChecked(prevState => !prevState);
+ };
+
+ const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
+ e.preventDefault();
+ if (!(e.target instanceof HTMLFormElement)) return;
+
+ const formElement = e.target.elements;
+ const getInputValue = createInputValueGetter(formElement);
+ const user = {
+ username: getInputValue('id'),
+ password: getInputValue('password'),
+ };
+
+ try {
+ const userInfo = await authAPI.login(user, checked);
+
+ dispatch(userActions.setUser(userInfo));
+ navigate(PATH.BASE);
+ } catch (error) {
+ if (error instanceof Error) {
+ alert(USER_MESSAGE.FAIL_LOGIN);
+ }
+ }
+ };
+
+ return (
+ <StyledForm onSubmit={handleSubmit}>
+ <label htmlFor="id">์์ด๋</label>
+ <input id="id" type="text" placeholder="์์ด๋๋ฅผ ์
๋ ฅํด์ฃผ์ธ์" required />
+ <label htmlFor="password">๋น๋ฐ๋ฒํธ</label>
+ <input
+ id="password"
+ type="password"
+ placeholder="๋น๋ฐ๋ฒํธ๋ฅผ ์
๋ ฅํด์ฃผ์ธ์"
+ required
+ />
+ <StyledLoginHelper>
+ <StyledKeepLogin>
+ <CheckBox
+ id="keep-login"
+ checked={checked}
+ onChange={toggleChecked}
+ marginBottom="0px"
+ />
+ <label htmlFor="keep-login">๋ก๊ทธ์ธ ์ํ ์ ์ง</label>
+ </StyledKeepLogin>
+ <StyledFindLoginInfo>
+ <Link to="#">์์ด๋ ์ฐพ๊ธฐ</Link>
+ <Link to="#">๋น๋ฐ๋ฒํธ ์ฐพ๊ธฐ</Link>
+ </StyledFindLoginInfo>
+ </StyledLoginHelper>
+ <StyledLoginButton type="submit">๋ก๊ทธ์ธ</StyledLoginButton>
+ </StyledForm>
+ );
+}
+
+const StyledForm = styled.form`
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+
+ width: 100%;
+
+ > label {
+ margin-top: 10px;
+ font-size: 14px;
+ }
+
+ > input {
+ border: 1px solid ${({ theme: { colors } }) => colors.lightGray};
+ border-radius: 2px;
+ padding: 6px 8px;
+ }
+`;
+
+const StyledLoginHelper = styled.div`
+ display: flex;
+ justify-content: space-between;
+ margin-top: 4px;
+ width: 100%;
+`;
+
+const StyledKeepLogin = styled.div`
+ display: flex;
+ align-items: center;
+ gap: 5px;
+
+ > label {
+ font-size: 10px;
+ }
+`;
+
+const StyledFindLoginInfo = styled.div`
+ display: flex;
+ align-items: center;
+ gap: 10px;
+
+ color: ${({ theme: { colors } }) => colors.gray};
+
+ font-size: 10px;
+
+ a:hover {
+ font-weight: 900;
+ }
+`;
+
+const StyledLoginButton = styled.button`
+ background: ${({ theme: { colors } }) => colors.redPink};
+ color: ${({ theme: { colors } }) => colors.white};
+ border-radius: 5px;
+
+ height: 40px;
+ margin-top: 20px;
+
+ font-size: 17px;
+ font-weight: 900;
+`;
+
+export default LoginForm; | Unknown | ์๊ฐ์ด ๋๋ค๋ฉด import ๋ฌธ๋ค์ ์์๋ฅผ ์ ๋ฆฌํด์ฃผ๋๊ฒ๋ ์ข์ ๊ฒ ๊ฐ์์!
hooks๋ ๋ณดํต ์ต์์์์ ๋ถ๋ฌ์์ฃผ๋๊ฒ์ผ๋ก ์๊ณ ์์ต๋๋ค! |
@@ -0,0 +1,37 @@
+import { ApolloServer } from 'apollo-server';
+
+import typeDefs from './typeDefs';
+import resolvers from './resolvers';
+
+import model from './database/models';
+import * as jwtManager from './util/jwt-manager';
+
+// Set GraphQL Apollo server
+const context = ({ req }) => {
+ const authorizationHeader = req.headers.authorization || '';
+ const token = authorizationHeader.split(' ')[1];
+ const user = jwtManager.isTokenValid(token);
+
+ return { user, model };
+};
+
+const formatError = err => {
+ console.error('--- GraphQL Error ---');
+ console.error('Path:', err.path);
+ console.error('Message:', err.message);
+ console.error('Code:', err.extensions.code);
+ console.error('Original Error', err.originalError);
+ return err;
+};
+
+const server = new ApolloServer({
+ typeDefs,
+ resolvers,
+ context,
+ formatError,
+ debug: false,
+});
+
+server.listen().then(({ url }) => {
+ console.log(`๐ Server ready at ${url}`);
+}); | JavaScript | `authorization`์ด ์์๋์ ์ฒ๋ฆฌ๊ฐ ์ข๋ค์~ |
@@ -0,0 +1,37 @@
+import { ApolloServer } from 'apollo-server';
+
+import typeDefs from './typeDefs';
+import resolvers from './resolvers';
+
+import model from './database/models';
+import * as jwtManager from './util/jwt-manager';
+
+// Set GraphQL Apollo server
+const context = ({ req }) => {
+ const authorizationHeader = req.headers.authorization || '';
+ const token = authorizationHeader.split(' ')[1];
+ const user = jwtManager.isTokenValid(token);
+
+ return { user, model };
+};
+
+const formatError = err => {
+ console.error('--- GraphQL Error ---');
+ console.error('Path:', err.path);
+ console.error('Message:', err.message);
+ console.error('Code:', err.extensions.code);
+ console.error('Original Error', err.originalError);
+ return err;
+};
+
+const server = new ApolloServer({
+ typeDefs,
+ resolvers,
+ context,
+ formatError,
+ debug: false,
+});
+
+server.listen().then(({ url }) => {
+ console.log(`๐ Server ready at ${url}`);
+}); | JavaScript | `token`, `user`์ ๋ง๋๋ ๊ตฌ๋ฌธ์ ์ด์ฐจํผ `authorization`์ด ์์ผ๋ฉด ๋ฌดํจํ ๋ก์ง์ผ๋ก ๋ณด์ด๋๋ฐ์
๋ณ๋์ ํ๋ฆ์ ๋ง๋ค๊ฑฐ๋ ๋ณ๋์ ํจ์๋ก ๋ถ๋ฆฌํ์ง ์์ ์ด์ ๊ฐ ์์๊น์?
๋ํ `[1]`์ผ๋ก ๋ฐฐ์ด์์ ์์ดํ
์ ํฝํด์ค๋ ๊ฒ์ ์์์ ์ผ๋ก ๋๊ปด์ง๋๋ฐ์.
๋ช
์์ ์ผ๋ก ๋ณ๊ฒฝํด๋ณด์๋๊ฑด ์ด๋จ๊น์? |
@@ -0,0 +1,38 @@
+// import dotenv from 'dotenv';
+const dotenv = require('dotenv');
+dotenv.config();
+
+const {
+ DB_DEV_USER,
+ DB_DEV_PASSWORD,
+ DB_DEV_DATABASE,
+ DB_DEV_HOST,
+ DB_PRODUCTION_USER,
+ DB_PRODUCTION_PASSWORD,
+ DB_PRODUCTION_DATABASE,
+ DB_PRODUCTION_HOST,
+} = process.env;
+
+module.exports = {
+ development: {
+ username: DB_DEV_USER,
+ password: DB_DEV_PASSWORD,
+ database: DB_DEV_DATABASE,
+ host: DB_DEV_HOST,
+ dialect: 'mysql',
+ },
+ test: {
+ username: DB_DEV_USER,
+ password: DB_DEV_PASSWORD,
+ database: DB_DEV_DATABASE,
+ host: DB_DEV_HOST,
+ dialect: 'mysql',
+ },
+ production: {
+ username: DB_PRODUCTION_USER,
+ password: DB_PRODUCTION_PASSWORD,
+ database: DB_PRODUCTION_DATABASE,
+ host: DB_PRODUCTION_HOST,
+ dialect: 'mysql',
+ },
+}; | JavaScript | ๋ถํ์ํ ์ฃผ์์ผ๋ก ๋ณด์
๋๋ค~ |
@@ -0,0 +1,38 @@
+// import dotenv from 'dotenv';
+const dotenv = require('dotenv');
+dotenv.config();
+
+const {
+ DB_DEV_USER,
+ DB_DEV_PASSWORD,
+ DB_DEV_DATABASE,
+ DB_DEV_HOST,
+ DB_PRODUCTION_USER,
+ DB_PRODUCTION_PASSWORD,
+ DB_PRODUCTION_DATABASE,
+ DB_PRODUCTION_HOST,
+} = process.env;
+
+module.exports = {
+ development: {
+ username: DB_DEV_USER,
+ password: DB_DEV_PASSWORD,
+ database: DB_DEV_DATABASE,
+ host: DB_DEV_HOST,
+ dialect: 'mysql',
+ },
+ test: {
+ username: DB_DEV_USER,
+ password: DB_DEV_PASSWORD,
+ database: DB_DEV_DATABASE,
+ host: DB_DEV_HOST,
+ dialect: 'mysql',
+ },
+ production: {
+ username: DB_PRODUCTION_USER,
+ password: DB_PRODUCTION_PASSWORD,
+ database: DB_PRODUCTION_DATABASE,
+ host: DB_PRODUCTION_HOST,
+ dialect: 'mysql',
+ },
+}; | JavaScript | ์ข์ ์ต๊ด์
๋๋ค ๐ |
@@ -0,0 +1,19 @@
+FROM node:11.11.0
+
+# ์ฑ ๋๋ ํฐ๋ฆฌ ์์ฑ
+WORKDIR /usr/src/app
+
+# ์ฑ ์์กด์ฑ ์ค์น
+# ๊ฐ๋ฅํ ๊ฒฝ์ฐ(npm@5+) package.json๊ณผ package-lock.json์ ๋ชจ๋ ๋ณต์ฌํ๊ธฐ ์ํด
+# ์์ผ๋์นด๋๋ฅผ ์ฌ์ฉ
+COPY package*.json ./
+
+RUN npm install
+# ํ๋ก๋์
์ ์ํ ์ฝ๋๋ฅผ ๋น๋ํ๋ ๊ฒฝ์ฐ
+# RUN npm ci --only=production
+
+# ์ฑ ์์ค ์ถ๊ฐ
+COPY . .
+
+EXPOSE 4000
+CMD [ "npm", "start" ]
\ No newline at end of file | Unknown | `RUN npm ci --only=production`๋ก ์นํํ๋๊ฒ ๋ ๋ฐ๋์งํด๋ณด์ด๋ค์ :) |
@@ -0,0 +1,38 @@
+// import dotenv from 'dotenv';
+const dotenv = require('dotenv');
+dotenv.config();
+
+const {
+ DB_DEV_USER,
+ DB_DEV_PASSWORD,
+ DB_DEV_DATABASE,
+ DB_DEV_HOST,
+ DB_PRODUCTION_USER,
+ DB_PRODUCTION_PASSWORD,
+ DB_PRODUCTION_DATABASE,
+ DB_PRODUCTION_HOST,
+} = process.env;
+
+module.exports = {
+ development: {
+ username: DB_DEV_USER,
+ password: DB_DEV_PASSWORD,
+ database: DB_DEV_DATABASE,
+ host: DB_DEV_HOST,
+ dialect: 'mysql',
+ },
+ test: {
+ username: DB_DEV_USER,
+ password: DB_DEV_PASSWORD,
+ database: DB_DEV_DATABASE,
+ host: DB_DEV_HOST,
+ dialect: 'mysql',
+ },
+ production: {
+ username: DB_PRODUCTION_USER,
+ password: DB_PRODUCTION_PASSWORD,
+ database: DB_PRODUCTION_DATABASE,
+ host: DB_PRODUCTION_HOST,
+ dialect: 'mysql',
+ },
+}; | JavaScript | ํ๊ฒฝ๋ณ์๋ฅผ .envํ์ผ์ `DEV_`์ `PRODUCTION` ๊ตฌ๋ถ์ ๋์ด ์ ์ฅํ๋ ๊ฒ๋ณด๋ค
ํ๊ฒฝ๋ณ์๋ช
์ ์ผ์น์ํค๊ณ (=dev, prod ๊ตฌ๋ถ์์ด)
์ถ๊ฐ๋ก `.env.test`, `.env.dev` ์ ๊ฐ์ ํ์ผ์ ๋ง๋ค์ด ๊ด๋ฆฌํ๋๊ฑธ ์ถ์ฒ๋๋ฆฝ๋๋ค.
https://github.com/motdotla/dotenv#should-i-have-multiple-env-files |
@@ -0,0 +1,38 @@
+// import dotenv from 'dotenv';
+const dotenv = require('dotenv');
+dotenv.config();
+
+const {
+ DB_DEV_USER,
+ DB_DEV_PASSWORD,
+ DB_DEV_DATABASE,
+ DB_DEV_HOST,
+ DB_PRODUCTION_USER,
+ DB_PRODUCTION_PASSWORD,
+ DB_PRODUCTION_DATABASE,
+ DB_PRODUCTION_HOST,
+} = process.env;
+
+module.exports = {
+ development: {
+ username: DB_DEV_USER,
+ password: DB_DEV_PASSWORD,
+ database: DB_DEV_DATABASE,
+ host: DB_DEV_HOST,
+ dialect: 'mysql',
+ },
+ test: {
+ username: DB_DEV_USER,
+ password: DB_DEV_PASSWORD,
+ database: DB_DEV_DATABASE,
+ host: DB_DEV_HOST,
+ dialect: 'mysql',
+ },
+ production: {
+ username: DB_PRODUCTION_USER,
+ password: DB_PRODUCTION_PASSWORD,
+ database: DB_PRODUCTION_DATABASE,
+ host: DB_PRODUCTION_HOST,
+ dialect: 'mysql',
+ },
+}; | JavaScript | ์ด ๋ผ์ธ์ด ๊ผญ ์ฃผ์์ฒ๋ฆฌ ๋์ด์ผํ๋์ง ํ์ธํด๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค |
@@ -0,0 +1,31 @@
+'use strict';
+module.exports = {
+ up: (queryInterface, Sequelize) => {
+ return queryInterface.createTable('room_options', {
+ bed: {
+ type: Sequelize.INTEGER,
+ },
+ bedroom: {
+ type: Sequelize.INTEGER,
+ },
+ bathroom: {
+ type: Sequelize.INTEGER,
+ },
+ free_parking: {
+ type: Sequelize.BOOLEAN,
+ },
+ wifi: {
+ type: Sequelize.BOOLEAN,
+ },
+ kitchen: {
+ type: Sequelize.BOOLEAN,
+ },
+ washer: {
+ type: Sequelize.BOOLEAN,
+ },
+ });
+ },
+ down: (queryInterface, Sequelize) => {
+ return queryInterface.dropTable('room_options');
+ },
+}; | JavaScript | 'use strict'๋ฅผ ๊ผญ ์จ์ผํ๋์?
๋ง์ฝ ๊ผญ ํ์ํ๋ค๋ฉด, ์ด ๋ผ์ธ์ด ์๋ ํ์ผ๋ ์๋๋ฐ ์ฃผ์์ผ๋ก ์ค๋ช
์ ๋ฌ์๋์ผ๋ฉด ์ข์ ๊ฒ ๊ฐ๋ค์ :) |
@@ -0,0 +1,37 @@
+'use strict';
+
+module.exports = {
+ up: (queryInterface, Sequelize) => {
+ return queryInterface.bulkInsert(
+ 'users',
+ [
+ {
+ name: '์ผ์ง์',
+ email: 'init@init.com',
+ password: 'password',
+ salt: 'salt',
+ is_super_host: false,
+ },
+ {
+ name: '์ด์ง์',
+ email: 'init2@init.com',
+ password: 'password',
+ salt: 'salt',
+ is_super_host: false,
+ },
+ {
+ name: '์ผ์ง์',
+ email: 'init3@init.com',
+ password: 'password',
+ salt: 'salt',
+ is_super_host: false,
+ },
+ ],
+ {},
+ );
+ },
+
+ down: (queryInterface, Sequelize) => {
+ return queryInterface.bulkDelete('users', null, {});
+ },
+}; | JavaScript | mock ๋ฐ์ดํฐ์ง๋ง ์๋ช
์ผ์ค ๐ |
@@ -0,0 +1,38 @@
+// import dotenv from 'dotenv';
+const dotenv = require('dotenv');
+dotenv.config();
+
+const {
+ DB_DEV_USER,
+ DB_DEV_PASSWORD,
+ DB_DEV_DATABASE,
+ DB_DEV_HOST,
+ DB_PRODUCTION_USER,
+ DB_PRODUCTION_PASSWORD,
+ DB_PRODUCTION_DATABASE,
+ DB_PRODUCTION_HOST,
+} = process.env;
+
+module.exports = {
+ development: {
+ username: DB_DEV_USER,
+ password: DB_DEV_PASSWORD,
+ database: DB_DEV_DATABASE,
+ host: DB_DEV_HOST,
+ dialect: 'mysql',
+ },
+ test: {
+ username: DB_DEV_USER,
+ password: DB_DEV_PASSWORD,
+ database: DB_DEV_DATABASE,
+ host: DB_DEV_HOST,
+ dialect: 'mysql',
+ },
+ production: {
+ username: DB_PRODUCTION_USER,
+ password: DB_PRODUCTION_PASSWORD,
+ database: DB_PRODUCTION_DATABASE,
+ host: DB_PRODUCTION_HOST,
+ dialect: 'mysql',
+ },
+}; | JavaScript | ์ค๋ณต๋๋ ์ฝ๋๋ ๊ฐ๋ฅํ๋ฉด ์ค์ด๋ ๊ฒ์ด ์ข์ต๋๋ค. ์๋ํ๋ฉด ์ง๊ธ์ ์ฝ๋๊ฐ ๋ง์ง ์์์ ๋ฌธ์ ๊ฐ ์๋ค๊ณ ๋๋ ์๋ ์์ง๋ง, ์ดํ ๋ณต์ก๋๊ฐ ์ฆ๊ฐํ๋ฉด ์ฝ๋๋ฅผ ์์ ํ ๋ ์ ์ง๋ณด์์ ์ธก๋ฉด์์ ๋ฒ๊ทธ๊ฐ ๋ฐ์ํ ์ ์๋ ๊ฐ๋ฅ์ฑ์ด ๋์์ง๊ธฐ ๋๋ฌธ์
๋๋ค. `DRY(Don't Repeat Yourself)` ์์น์ ์ดํ๋ก๋ ํญ์ ๊ธฐ์ตํ๊ณ ์ฝ๋๋ฅผ ์์ฑํ๋ ๊ฒ์ด ๋ฐ๋์งํ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,37 @@
+import fs from 'fs';
+import path from 'path';
+import Sequelize from 'sequelize';
+import configs from '../../config/database.js';
+
+const basename = path.basename(__filename);
+const env = process.env.NODE_ENV || 'development';
+const config = configs[env];
+
+const db = {};
+
+let sequelize;
+if (config.use_env_variable) {
+ sequelize = new Sequelize(process.env[config.use_env_variable], config);
+} else {
+ sequelize = new Sequelize(config.database, config.username, config.password, config);
+}
+
+fs.readdirSync(__dirname)
+ .filter(file => {
+ return file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js';
+ })
+ .forEach(file => {
+ const model = sequelize['import'](path.join(__dirname, file));
+ db[model.name] = model;
+ });
+
+Object.keys(db).forEach(modelName => {
+ if (db[modelName].associate) {
+ db[modelName].associate(db);
+ }
+});
+
+db.sequelize = sequelize;
+db.Sequelize = Sequelize;
+
+module.exports = db; | JavaScript | db ๊ฐ์ฒด์ ํ๋๊ฐ์ด ์ด๋ ๊ฒ ๋น์ทํ๋ฉด ์ดํ์ ํท๊ฐ๋ฆฌ๊ธฐ ์ฌ์ธ ๊ฒ ๊ฐ์ต๋๋ค. ๋ณ์ ๋ช
์ ์กฐ๊ธ ๋ ๋ช
ํํ๊ฒ ๊ตฌ๋ถ์ ํด ์ฃผ๋ ๊ฒ๋ ์ข์ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,28 @@
+'use strict';
+
+module.exports = {
+ up: (queryInterface, Sequelize) => {
+ return queryInterface.bulkInsert(
+ 'room_types',
+ [
+ {
+ name: '์ง ์ ์ฒด',
+ },
+ {
+ name: '๊ฐ์ธ์ค',
+ },
+ {
+ name: 'ํธํ
๊ฐ์ค',
+ },
+ {
+ name: '๋ค์ธ์ค',
+ },
+ ],
+ {},
+ );
+ },
+
+ down: (queryInterface, Sequelize) => {
+ return queryInterface.bulkDelete('room_types', null, {});
+ },
+}; | JavaScript | ๊ฐ์ค์ ๋ถ์ฌ์ ์จ์ผ ํ๋๋ฐ ์คํ์ธ ๊ฒ ๊ฐ๋ค์ |
@@ -0,0 +1,13 @@
+NODE_ENV=
+
+DB_DEV_USER=
+DB_DEV_PASSWORD=
+DB_DEV_DATABASE=
+DB_DEV_HOST=
+
+DB_PRODUCTION_USER=
+DB_PRODUCTION_PASSWORD=
+DB_PRODUCTION_DATABASE=
+DB_PRODUCTION_HOST=
+
+TOKEN_SECRET_KEY=
\ No newline at end of file | Unknown | .env ํ์ผ์ ์ค์ ๋ก ์ฌ์ฉํ ๋๋ ๋ฏผ๊ฐํ ์ ๋ณด๋ค์ด ๋ง์ด ์์ ์ ์์ผ๋ .dev.env ํํ๋ก github์์ ๋ณด์ด์ง ์๊ฒ ํด์ฃผ๋ ๊ฒ๋ ๋ณด์์ ์ข์ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,37 @@
+import fs from 'fs';
+import path from 'path';
+import Sequelize from 'sequelize';
+import configs from '../../config/database.js';
+
+const basename = path.basename(__filename);
+const env = process.env.NODE_ENV || 'development';
+const config = configs[env];
+
+const db = {};
+
+let sequelize;
+if (config.use_env_variable) {
+ sequelize = new Sequelize(process.env[config.use_env_variable], config);
+} else {
+ sequelize = new Sequelize(config.database, config.username, config.password, config);
+}
+
+fs.readdirSync(__dirname)
+ .filter(file => {
+ return file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js';
+ })
+ .forEach(file => {
+ const model = sequelize['import'](path.join(__dirname, file));
+ db[model.name] = model;
+ });
+
+Object.keys(db).forEach(modelName => {
+ if (db[modelName].associate) {
+ db[modelName].associate(db);
+ }
+});
+
+db.sequelize = sequelize;
+db.Sequelize = Sequelize;
+
+module.exports = db; | JavaScript | ํ ์ค์ด๋ผ๋ ๋ง์ฝ ํ ๋์ ๋ณด๊ธฐ์ ์กฐ๊ธ ๋ณต์กํ๋ค๋ ๋๋์ด ๋ ๋ค๋ฉด ๋ณ๋์ ํจ์ ํํ๋ก ์ธ๋ถ์ ๋นผ๋ ๊ฒ๋ ์ข์ ๊ฒ ๊ฐ์์. ์ดํ์ ์กฐ๊ฑด์ด ๋ ๋ถ๋๋ค๋ฉด ๊ทธ๋ ๊ฒ ํ๋ ๊ฒ์ ๊ถ์ฅํฉ๋๋ค. ๋ค๋ฅธ ๊ฐ๋ฐ์๊ฐ ์ฝ๋๋ฅผ ์ดํดํ๋๋ฐ ํจ์ฌ ๋ ๋์์ด ๋ ๊ฒ์
๋๋ค. |
@@ -0,0 +1,41 @@
+INSERT INTO board_entity (board_name)
+VALUES
+ ('์์ ๊ฒ์ํ'),
+ ('๊ฐ๋ฐ ๊ฒ์ํ'),
+ ('์ผ์ ๊ฒ์ํ'),
+ ('์ฌ๊ฑด์ฌ๊ณ ๊ฒ์ํ');
+
+INSERT INTO article_entity (title, content, password, board_id)
+VALUES
+ ('์๋์
๊ตฌ์ญ ๋ง์ง ์ถ์ฒ', '์๋์
๊ตฌ์ญ ๊ทผ์ฒ์ ์๋ ํํ๋จ์ ์๋น์ด ๋ง์์ด์!', '1234', 1),
+ ('์ฐ์ ํ๋ก๊ทธ๋จ์ ๋ณด๋ฉด์..', '๊ฐ๋ฐ์๋ค์ ์ํ ์๋ฅ ํ๋ก๊ทธ๋จ์ด ์์์ผ๋ฉด ์ข๊ฒ ๋ค.. ์ ๊ทผ๋ฐ ๊ฐ๋ฐ์๋ค์ด ์นด๋ฉ๋ผ ์์ ์ค๋ฆฌ๊ฐ ์์ง ใ
ใ
ใ
ใ
', '1234', 1),
+ ('GPT 3.5๋ฅผ ์ฐ๋ฉด์..', '๋ ๊ทธ๋ฅ ์ฝ๋ฉ ํ์ง ๋ง์๋ผ ์ ํฐ์ง๋ค.', '1234', 2),
+ ('JS์ Java๋ฅผ ๊ณต๋ถํ๋๊น', '๋๋ฌด ํท๊ฐ๋ ค์ ใ
ใ
ใ
๋งค๊ฐ๋ณ์ ๋ฃ์ ๋ ์๊พธ ํ์
์ ์์;;', '1234', 2),
+ ('๋ค์ด๋ฒ ๋ธ๋ก๊ทธ style ์ฝ๋ ๋ฆฌ๋ทฐ', '์ค๋์ ์ฝ๋ ๋ฆฌ๋ทฐ๋ฅผ ์์๋ณผ๊ฒ์! ์ ๋ ์ฐธ ๊ถ๊ธํ๋ค์!', '1234', 2),
+ ('์์ฆ ๊ทผํฉ', '๋ฐฅ ๋จน์ด ์ฝ๋ฉ ํด ๋ ๋ฐฅ ๋จน์ด ์ฝ๋ฉ ํด ์ ํ๋ธ ๋ด ๋ ์ฝ๋ฉ ํด', '1234', 3),
+ ('์์ฆ ๊ทผํฉ', '๋ฐฅ๋ฐฅ๋ฐฅ๋ฐฅ ์ค๋ ์ ๋
์ ์ ์ก๋ณถ์~~', '1234', 3),
+ ('์ฌ๊ฑด์ฌ๊ณ ? ๊ทธ๋ฐ๊ฑด ๋ด ์ฌ์ ์ ์๋ค.', '์๋ํ๋ฉด ์ฝ๋ฉ์ ํ ์ค๋ ์์น๊ธฐ ๋๋ฌธ์ด์ง ํํํ!', '1234', 4),
+ ('์ผ ์๋ฌ ๋จ๋ ๋๋ค ๋ด๋ผ ใ
ใ
ใ
', '์๋ฌ? ์๋ ์ปดํจํฐ ๋๊ฐ ํ๋ฆฌ๊ณ ๋ด๊ฐ ๋ง์ด', '1234', 4);
+
+INSERT INTO comment_entity(content, password, article_id)
+VALUES
+ ('ํํ๋จ์ ๊ฑฐ๊ธฐ ๋ง์์ด์!', '1234', 1),
+ ('์ธํ
๋ฆฌ์ด๊ฐ ์ด๋ป์!', '1234', 1),
+ ('๊ฐ๋ฐ์๋ฅผ ์ํ ์๋ฅ์ด๋ผ๋.. ์์ ๊ฟ์ ๊พธ์์ต๋๋ค..', '1234', 2),
+ ('์์ฃผ ํ๋ณตํ ๊ฟ์ด์์ต๋๋ค..', '1234', 2),
+ ('๊ทผ๋ฐ ์ ์ฐ๋ ๊ฒ์ด๋', '1234', 2),
+ ('๊ทธ๊ฑด ์ด๋ค์ง ์ ์๋ ๊ฟ์ด๊ธฐ ๋๋ฌธ์
๋๋ค.', '1234', 2),
+ ('GPT๋ ์คํ ์ก๊ธฐ ์ต๊ณ ๋ผ๊ณ ใ
ใ
ใ
ใ
', '1234', 3),
+ ('๋ฐฑ์๋์ ๊ทผ๋ณธ์ Java์ด์ง ใ
ใ
ใ
ใ
', '1234', 4),
+ ('js๋ ๊ทผ๋ณธ์ด ์๋ค ์์
๋๊บผ ๊ทผ๋ณธ์ด! ', '1234', 4),
+ ('์ด์ ์ด๋ ๊ฒ ๋๊ฑฐ ์ฝํ๋ฆฐ์ผ๋ก ๊ฐ๋ค.', '1234', 4),
+ ('์คํจํ๋ฉด ํ์
์คํฌ๋ฆฝํธ ์ฑ๊ณตํ๋ฉด ๋์ ์ธ์ด ์ต๊ณ ์๋๋๊น!.', '1234', 4),
+ ('ํ์
์คํฌ๋ฆฝํธ๋ Java๋ ํ์
์ฐ๋ ๋ฐฉ์์ด ๋ค๋ฆ ใ
ใ
ใ
ใ
์๊ณ ์.', '1234', 4),
+ ('๋น๋ฐ ๋๊ธ์
๋๋ค.', '1234', 5),
+ ('๋น๋ฐ ๋๊ธ์
๋๋ค.', '1234', 5),
+ ('๊ฐ๋ฐ ๊ณต๋ถํ๋ฉด ์๋ ๋ฐ์ฏค ๋ฏธ์ณ๊ฐ๋์?', '1234', 5),
+ ('์ผ์ ์๊ณ ๋ฆฌ์ฆ ํผ ๋ฏธ์ณค๋ค', '1234', 6),
+ ('๋ ์๋ ๊ธ ์ด ๋์ด์ง?', '1234', 7),
+ ('๊ฐ๋ฐ ๊ณต๋ถํ๋ฉด ์๋ ๋ฐ์ฏค ๋ฏธ์น๋์?', '1234', 7),
+ ('๊ทธ๋ฐ ๋ฐฉ๋ฒ์ด ์์๋ค ใ
ใ
ใ
ใ
ใ
ใ
', '1234', 8),
+ ('404 Not Found๋ผ๊ณ ? ๊ทธ๋ผ ์ฐพ์ด!', '1234', 9); | Unknown | yaml์ค์ create๋ผ ํ
์คํธ์ฉ ๋ฐ์ดํฐ ์ ๋ถ ์์ฑํด๋์ ์ฌ์ธํจ์ ๋๋์ต๋๋ค. |
@@ -0,0 +1,147 @@
+package com.subject.board.article;
+
+import com.subject.board.board.BoardService;
+import com.subject.board.comment.CommentService;
+import com.subject.board.entity.ArticleEntity;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.servlet.mvc.support.RedirectAttributes;
+
+import java.util.ArrayList;
+import java.util.List;
+
+
+@Controller
+@RequestMapping("/article")
+@RequiredArgsConstructor
+public class ArticleController {
+ private final ArticleService articleService;
+ private final BoardService boardService;
+ private final CommentService commentService;
+
+ // Create
+ // ๊ฒ์๊ธ ์์ฑ view๋ก ์ด๋
+ @GetMapping("/create")
+ public String createPage() {
+ return "article/create";
+ }
+
+ // create ๋ก์ง
+ @PostMapping("/create")
+ public String create(
+ @RequestParam("board-id") Long boardId,
+ @RequestParam("title") String title,
+ @RequestParam("content") String content,
+ @RequestParam("password") String password
+ ) {
+ articleService.create(boardId, title, content, password);
+ return "redirect:/article";
+ }
+
+ // Read
+ // ์ ์ฒด ๋ณด๊ธฐ(= ์ ์ฒด ๊ฒ์ํ)
+ @GetMapping
+ public String readAll(Model model) {
+ model.addAttribute("articles", articleService.readAll());
+ return "home";
+ }
+
+ // ์์ธ ๋ณด๊ธฐ
+ @GetMapping("/{articleId}")
+ public String readOne(
+ @PathVariable("articleId") Long articleId,
+ Model model
+ ) {
+ model.addAttribute("article", articleService.readOne(articleId));
+ model.addAttribute("comments", commentService.findByArticleId(articleId));
+ return "article/read";
+ }
+
+ // Update
+ // ๋น๋ฐ๋ฒํธ view
+ @GetMapping("/{articleId}/password-view/update")
+ public String passwordViewUpdate(
+ @PathVariable("articleId") Long articleId,
+ Model model
+ ) {
+ model.addAttribute("article", articleService.readOne(articleId));
+ model.addAttribute("type", "article");
+ model.addAttribute("method", "update");
+ return "password";
+ }
+
+ // ๋น๋ฐ๋ฒํธ ํ์ธ ํ -> update view๋ก ์ด๋
+ @PostMapping("/{articleId}/passwordCheck/update")
+ public String checkPasswordUpdate(
+ @PathVariable("articleId") Long articleId,
+ @RequestParam("input-password") String inputPassword,
+ RedirectAttributes redirectAttributes,
+ Model model
+ ) {
+ if (articleService.checkPassword(articleId, inputPassword)) {
+ // ๋น๋ฐ๋ฒํธ ์ผ์น
+ model.addAttribute("article", articleService.readOne(articleId));
+ model.addAttribute("boards", boardService.readAll());
+ return "article/update";
+ } else {
+ // ๋น๋ฐ๋ฒํธ ๋ถ์ผ์น
+ redirectAttributes.addFlashAttribute("error", "๋น๋ฐ๋ฒํธ๊ฐ ์ผ์นํ์ง ์์ต๋๋ค.");
+ return "redirect:/article/" + articleId + "/password-view/update"; // ๋ค์ ๋น๋ฐ๋ฒํธ ์
๋ ฅ ํ์ด์ง๋ก ๋ฆฌ๋ค์ด๋ ํธ
+ }
+ }
+
+ // update ์คํ
+ @PostMapping("/{articleId}/update")
+ public String update(
+ @PathVariable("articleId") Long articleId,
+ @RequestParam("board-id") Long boardId,
+ @RequestParam("title") String title,
+ @RequestParam("content") String content
+ ) {
+ articleService.update(articleId, boardId, title, content);
+ return String.format("redirect:/article/%d", articleId);
+ }
+
+ // Delete
+ // ๋น๋ฐ๋ฒํธ view
+ @GetMapping("/{articleId}/password-view/delete")
+ public String passwordViewDelete(
+ @PathVariable("articleId") Long articleId,
+ Model model
+ ) {
+ model.addAttribute("article", articleService.readOne(articleId));
+ model.addAttribute("type", "article");
+ model.addAttribute("method", "delete");
+ return "password";
+ }
+
+ // ๋น๋ฐ๋ฒํธ๊ฐ ์ผ์นํ๋ฉด ์ญ์ , ํ๋ฆฌ๋ฉด ๊ฒฝ๊ณ ์ฐฝ
+ @PostMapping("/{articleId}/passwordCheck/delete")
+ public String checkPasswordDelete(
+ @PathVariable("articleId") Long articleId,
+ @RequestParam("input-password") String inputPassword,
+ RedirectAttributes redirectAttributes,
+ Model model
+ ) {
+ if (articleService.checkPassword(articleId, inputPassword)) {
+ articleService.delete(articleId);
+ return "redirect:/article";
+ } else {
+ redirectAttributes.addFlashAttribute("error", "๋น๋ฐ๋ฒํธ๊ฐ ์ผ์นํ์ง ์์ต๋๋ค.");
+ return "redirect:/article/" + articleId + "/password-view/delete"; // ๋ค์ ๋น๋ฐ๋ฒํธ ์
๋ ฅ ํ์ด์ง๋ก ๋ฆฌ๋ค์ด๋ ํธ
+ }
+ }
+
+ // Search
+ @PostMapping("/search")
+ public String searchArticle(
+ @RequestParam("category") String category,
+ @RequestParam("search") String search,
+ Model model
+ ) {
+ model.addAttribute("articles", articleService.search(category, search));
+ return "article/searchArticle";
+ }
+} | Java | ์ ์ฒด ๊ฒ์๊ธ์์ ๊ฒ์๊ธ ์์ฑ์ ์๋ํ๋ ๊ฒ์๊ธ ์ฃผ์ ๋ฅผ ์ ํํ๋ ๋๋กญ๋ค์ด์ ์๋ฌด๊ฒ๋ ๋์ค์ง ์์ต๋๋ค.
๊ฒ์ํ์ ์ ๋ณด๋ฅผ model์ ๋ด์ ์ ๋ฌํ๋ ๊ณผ์ ์ด ๋น ์ง ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,147 @@
+package com.subject.board.article;
+
+import com.subject.board.board.BoardService;
+import com.subject.board.comment.CommentService;
+import com.subject.board.entity.ArticleEntity;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.servlet.mvc.support.RedirectAttributes;
+
+import java.util.ArrayList;
+import java.util.List;
+
+
+@Controller
+@RequestMapping("/article")
+@RequiredArgsConstructor
+public class ArticleController {
+ private final ArticleService articleService;
+ private final BoardService boardService;
+ private final CommentService commentService;
+
+ // Create
+ // ๊ฒ์๊ธ ์์ฑ view๋ก ์ด๋
+ @GetMapping("/create")
+ public String createPage() {
+ return "article/create";
+ }
+
+ // create ๋ก์ง
+ @PostMapping("/create")
+ public String create(
+ @RequestParam("board-id") Long boardId,
+ @RequestParam("title") String title,
+ @RequestParam("content") String content,
+ @RequestParam("password") String password
+ ) {
+ articleService.create(boardId, title, content, password);
+ return "redirect:/article";
+ }
+
+ // Read
+ // ์ ์ฒด ๋ณด๊ธฐ(= ์ ์ฒด ๊ฒ์ํ)
+ @GetMapping
+ public String readAll(Model model) {
+ model.addAttribute("articles", articleService.readAll());
+ return "home";
+ }
+
+ // ์์ธ ๋ณด๊ธฐ
+ @GetMapping("/{articleId}")
+ public String readOne(
+ @PathVariable("articleId") Long articleId,
+ Model model
+ ) {
+ model.addAttribute("article", articleService.readOne(articleId));
+ model.addAttribute("comments", commentService.findByArticleId(articleId));
+ return "article/read";
+ }
+
+ // Update
+ // ๋น๋ฐ๋ฒํธ view
+ @GetMapping("/{articleId}/password-view/update")
+ public String passwordViewUpdate(
+ @PathVariable("articleId") Long articleId,
+ Model model
+ ) {
+ model.addAttribute("article", articleService.readOne(articleId));
+ model.addAttribute("type", "article");
+ model.addAttribute("method", "update");
+ return "password";
+ }
+
+ // ๋น๋ฐ๋ฒํธ ํ์ธ ํ -> update view๋ก ์ด๋
+ @PostMapping("/{articleId}/passwordCheck/update")
+ public String checkPasswordUpdate(
+ @PathVariable("articleId") Long articleId,
+ @RequestParam("input-password") String inputPassword,
+ RedirectAttributes redirectAttributes,
+ Model model
+ ) {
+ if (articleService.checkPassword(articleId, inputPassword)) {
+ // ๋น๋ฐ๋ฒํธ ์ผ์น
+ model.addAttribute("article", articleService.readOne(articleId));
+ model.addAttribute("boards", boardService.readAll());
+ return "article/update";
+ } else {
+ // ๋น๋ฐ๋ฒํธ ๋ถ์ผ์น
+ redirectAttributes.addFlashAttribute("error", "๋น๋ฐ๋ฒํธ๊ฐ ์ผ์นํ์ง ์์ต๋๋ค.");
+ return "redirect:/article/" + articleId + "/password-view/update"; // ๋ค์ ๋น๋ฐ๋ฒํธ ์
๋ ฅ ํ์ด์ง๋ก ๋ฆฌ๋ค์ด๋ ํธ
+ }
+ }
+
+ // update ์คํ
+ @PostMapping("/{articleId}/update")
+ public String update(
+ @PathVariable("articleId") Long articleId,
+ @RequestParam("board-id") Long boardId,
+ @RequestParam("title") String title,
+ @RequestParam("content") String content
+ ) {
+ articleService.update(articleId, boardId, title, content);
+ return String.format("redirect:/article/%d", articleId);
+ }
+
+ // Delete
+ // ๋น๋ฐ๋ฒํธ view
+ @GetMapping("/{articleId}/password-view/delete")
+ public String passwordViewDelete(
+ @PathVariable("articleId") Long articleId,
+ Model model
+ ) {
+ model.addAttribute("article", articleService.readOne(articleId));
+ model.addAttribute("type", "article");
+ model.addAttribute("method", "delete");
+ return "password";
+ }
+
+ // ๋น๋ฐ๋ฒํธ๊ฐ ์ผ์นํ๋ฉด ์ญ์ , ํ๋ฆฌ๋ฉด ๊ฒฝ๊ณ ์ฐฝ
+ @PostMapping("/{articleId}/passwordCheck/delete")
+ public String checkPasswordDelete(
+ @PathVariable("articleId") Long articleId,
+ @RequestParam("input-password") String inputPassword,
+ RedirectAttributes redirectAttributes,
+ Model model
+ ) {
+ if (articleService.checkPassword(articleId, inputPassword)) {
+ articleService.delete(articleId);
+ return "redirect:/article";
+ } else {
+ redirectAttributes.addFlashAttribute("error", "๋น๋ฐ๋ฒํธ๊ฐ ์ผ์นํ์ง ์์ต๋๋ค.");
+ return "redirect:/article/" + articleId + "/password-view/delete"; // ๋ค์ ๋น๋ฐ๋ฒํธ ์
๋ ฅ ํ์ด์ง๋ก ๋ฆฌ๋ค์ด๋ ํธ
+ }
+ }
+
+ // Search
+ @PostMapping("/search")
+ public String searchArticle(
+ @RequestParam("category") String category,
+ @RequestParam("search") String search,
+ Model model
+ ) {
+ model.addAttribute("articles", articleService.search(category, search));
+ return "article/searchArticle";
+ }
+} | Java | ์ ๊ฐ ๋ฑ ์ํ๋ ๊ธฐ๋ฅ์ด์๋๋ฐ ์ด๋ ๊ฒ ๊ตฌํํ๋ ๊ฒ์ด์๊ตฐ์! ์ ๋ฐฐ์๊ฐ๋๋ค. |
@@ -0,0 +1,21 @@
+package com.subject.board.entity;
+
+import jakarta.persistence.*;
+import lombok.Data;
+import lombok.Getter;
+import lombok.Setter;
+
+import java.util.List;
+
+@Getter
+@Setter
+@Entity
+public class BoardEntity {
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Long id;
+ private String boardName;
+ @OneToMany(mappedBy = "board")
+ @OrderBy("id DESC") // article์ id๋ฅผ ๋ด๋ฆผ์ฐจ์์ผ๋ก ์ ๋ ฌ
+ private List<ArticleEntity> articles;
+} | Java | entity์์ article์ id๋ฅผ ์ ๋ ฌํด ๋ถ๊ฐ์ ์ธ ์ฝ๋์ ์ถ๊ฐ ์์ด ๊ฐ๋จํ๊ฒ ๊ฒ์๊ธ์ ์ ๋ ฌํ ์ ์์๋ค์. ๋ฐฐ์ฐ๊ณ ๊ฐ๋๋ค. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.