code stringlengths 41 34.3k | lang stringclasses 8
values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,15 @@
+package config;
+
+import controller.UserController;
+import service.UserJoinService;
+
+public class AppConfig {
+
+ public static UserController userController() {
+ return new UserController(userJoinService());
+ }
+
+ public static UserJoinService userJoinService() {
+ return new UserJoinService();
+ }
+} | Java | AppConfig๋ก DI๋ฅผ ์ฃผ์
ํด์ฃผ๋ ค๋ ์๋๐ |
@@ -0,0 +1,45 @@
+package controller;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import service.UserJoinService;
+import util.HttpRequest;
+import util.HttpResponse;
+
+public class UserController {
+ private final String HTTP_GET = "GET";
+ private final String JOIN_FORM = "/user/form.html";
+ private final String CREATE_USER_URL = "/user/create";
+ private UserJoinService userJoinService;
+ private Logger log = LoggerFactory.getLogger(getClass());
+
+ public UserController(UserJoinService userJoinService) {
+ this.userJoinService = userJoinService;
+ }
+
+ // TODO : ์๋ฌํ์ด์ง ์์ฑ, ํ์๊ฐ์
๊ฒ์ฆ
+ public String process(HttpRequest request, HttpResponse response) {
+ // GET ์์ฒญ์ธ ๊ฒฝ์ฐ ๋ถ๋ฆฌ
+ if (request.getMethod().equals(HTTP_GET)) {
+ // ํ์ ๊ฐ์
ํผ ๋ณด์ฌ์ฃผ๊ธฐ
+ if (request.getUrl().equals(JOIN_FORM)) {
+ return JOIN_FORM;
+ }
+ // ํ์๊ฐ์
์ผ ๊ฒฝ์ฐ
+ if (request.getUrl().equals(CREATE_USER_URL)) {
+ return addUser(request.getQueryString(), response);
+ }
+ }
+
+ return "/error";
+ }
+
+ private String addUser(String queryParameters, HttpResponse response) {
+ userJoinService.addUser(queryParameters);
+
+ response.setStatus(302);
+ response.setHeader("Location", "/index.html");
+ return response.getResponse();
+ }
+
+} | Java | ```suggestion
if (request.getUrl().equals(JOIN_FORM)) {
return JOIN_FORM;
}
```
๋ ๊ฐ ๊ฐ์ด ๊ฐ์์ ์ด ์ฝ๋์ ๊ฐ์ ์๋ฏธ์
๋๋ค. |
@@ -0,0 +1,45 @@
+package controller;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import service.UserJoinService;
+import util.HttpRequest;
+import util.HttpResponse;
+
+public class UserController {
+ private final String HTTP_GET = "GET";
+ private final String JOIN_FORM = "/user/form.html";
+ private final String CREATE_USER_URL = "/user/create";
+ private UserJoinService userJoinService;
+ private Logger log = LoggerFactory.getLogger(getClass());
+
+ public UserController(UserJoinService userJoinService) {
+ this.userJoinService = userJoinService;
+ }
+
+ // TODO : ์๋ฌํ์ด์ง ์์ฑ, ํ์๊ฐ์
๊ฒ์ฆ
+ public String process(HttpRequest request, HttpResponse response) {
+ // GET ์์ฒญ์ธ ๊ฒฝ์ฐ ๋ถ๋ฆฌ
+ if (request.getMethod().equals(HTTP_GET)) {
+ // ํ์ ๊ฐ์
ํผ ๋ณด์ฌ์ฃผ๊ธฐ
+ if (request.getUrl().equals(JOIN_FORM)) {
+ return JOIN_FORM;
+ }
+ // ํ์๊ฐ์
์ผ ๊ฒฝ์ฐ
+ if (request.getUrl().equals(CREATE_USER_URL)) {
+ return addUser(request.getQueryString(), response);
+ }
+ }
+
+ return "/error";
+ }
+
+ private String addUser(String queryParameters, HttpResponse response) {
+ userJoinService.addUser(queryParameters);
+
+ response.setStatus(302);
+ response.setHeader("Location", "/index.html");
+ return response.getResponse();
+ }
+
+} | Java | response ๊ตฌ์กฐ๋ฅผ ์ ๊ทน ์ฝ๋์ ๋ฐ์ํ์
จ๋ค์! |
@@ -0,0 +1,45 @@
+package controller;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import service.UserJoinService;
+import util.HttpRequest;
+import util.HttpResponse;
+
+public class UserController {
+ private final String HTTP_GET = "GET";
+ private final String JOIN_FORM = "/user/form.html";
+ private final String CREATE_USER_URL = "/user/create";
+ private UserJoinService userJoinService;
+ private Logger log = LoggerFactory.getLogger(getClass());
+
+ public UserController(UserJoinService userJoinService) {
+ this.userJoinService = userJoinService;
+ }
+
+ // TODO : ์๋ฌํ์ด์ง ์์ฑ, ํ์๊ฐ์
๊ฒ์ฆ
+ public String process(HttpRequest request, HttpResponse response) {
+ // GET ์์ฒญ์ธ ๊ฒฝ์ฐ ๋ถ๋ฆฌ
+ if (request.getMethod().equals(HTTP_GET)) {
+ // ํ์ ๊ฐ์
ํผ ๋ณด์ฌ์ฃผ๊ธฐ
+ if (request.getUrl().equals(JOIN_FORM)) {
+ return JOIN_FORM;
+ }
+ // ํ์๊ฐ์
์ผ ๊ฒฝ์ฐ
+ if (request.getUrl().equals(CREATE_USER_URL)) {
+ return addUser(request.getQueryString(), response);
+ }
+ }
+
+ return "/error";
+ }
+
+ private String addUser(String queryParameters, HttpResponse response) {
+ userJoinService.addUser(queryParameters);
+
+ response.setStatus(302);
+ response.setHeader("Location", "/index.html");
+ return response.getResponse();
+ }
+
+} | Java | ์ด ๋ถ๋ถ์ ์์ ๊ณ ๋ฒ์ฉ์ ์ธ ๋ฉ์๋๋ก ๋ฐ๋ก ๋นผ์ ๋ฆฌํฉํ ๋งํ ์ ์์ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,56 @@
+package util;
+
+public class HttpRequest {
+
+ private String method;
+ private String url;
+ private String queryString;
+
+ public HttpRequest(String line) {
+ String[] splitHeader = line.split(" ");
+ // uriPath = ์ ์ฒด uri (์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ ๋ถ๋ฆฌ ์ )
+ String uriPath = getURIPath(splitHeader);
+
+ // ์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ ๋ถ๋ฆฌ ํ url
+ this.url = getPath(uriPath);
+ this.method = splitHeader[0];
+ this.queryString = getQueryParameters(uriPath);
+ }
+
+ public String getMethod() {
+ return method;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public String getQueryString() {
+ return queryString;
+ }
+
+ @Override
+ public String toString() {
+ return "HttpRequest{" +
+ "method='" + method + '\'' +
+ ", url='" + url + '\'' +
+ ", queryString='" + queryString + '\'' +
+ '}';
+ }
+
+ private String getURIPath(String[] splitHeader) {
+ return splitHeader[1];
+ }
+
+ private String getPath(String uriPath) {
+ return uriPath.split("\\?")[0];
+ }
+
+ private String getQueryParameters(String uriPath) {
+ String[] split = uriPath.split("\\?");
+ if (split.length > 1) {
+ return split[1];
+ }
+ return "";
+ }
+} | Java | ์ฟผ๋ฆฌ๋ฅผ String์ผ๋ก ์ ์ฅํ๋๋ก ๊ตฌํํ์ ์ด์ ๊ฐ ์๋์? |
@@ -0,0 +1,81 @@
+package util;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.DataOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.util.HashMap;
+import java.util.Map;
+
+public class HttpResponse {
+
+ private Logger log = LoggerFactory.getLogger(getClass());
+ private int status;
+ private Map<String, String> headers = new HashMap<>();
+
+ public void processResponse(String path, HttpResponse response, OutputStream out) throws IOException {
+ String contentType = response.getContentType(path);
+ byte[] body = findBody(contentType, path);
+ DataOutputStream dos = new DataOutputStream(out);
+ responseHeader(dos, body.length, contentType);
+ responseBody(dos, body);
+ }
+
+
+ private void responseHeader(DataOutputStream dos, int lengthOfBodyContent, String contentType) {
+ try {
+ dos.writeBytes("HTTP/1.1 " + status + " " + getStatusCode(status) + "\r\n");
+ dos.writeBytes("Content-Type: " + contentType + "\r\n");
+ dos.writeBytes("Content-Length: " + lengthOfBodyContent + "\r\n");
+
+ for (Map.Entry<String, String> header : headers.entrySet()) {
+ dos.writeBytes(header.getKey() + ": " + header.getValue() + "\r\n");
+ }
+
+ dos.writeBytes("\r\n");
+ } catch (IOException e) {
+ log.error(e.getMessage());
+ }
+ }
+
+ private void responseBody(DataOutputStream dos, byte[] body) {
+ try {
+ dos.write(body, 0, body.length);
+ dos.flush();
+ } catch (IOException e) {
+ log.error(e.getMessage());
+ }
+ }
+
+ private String getContentType(String path) {
+ return ContentType.findContentType(path).getValue();
+ }
+
+ private byte[] findBody(String contentType, String path) throws IOException {
+ return Files.readAllBytes(new File(ResponseBody.findResponseBody(contentType).getPath() + path).toPath());
+ }
+
+ public void setStatus(int status) {
+ this.status = status;
+ }
+
+ public void setHeader(String name, String value) {
+ headers.put(name, value);
+ }
+
+ private String getStatusCode(int status) {
+ if (status == HttpStatus.MOVED_TEMPORARILY.getValue()) {
+ return HttpStatus.MOVED_TEMPORARILY.getReason();
+ }
+
+ return HttpStatus.OK.getReason();
+ }
+
+ public String getResponse() {
+ return headers.getOrDefault("Location", "");
+ }
+} | Java | path๊ฐ `/fonts/~` ์ด๋ ๊ฒ ์์ฒญ๋ค์ด์ค์ง ์๋์? |
@@ -0,0 +1,81 @@
+package util;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.DataOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.util.HashMap;
+import java.util.Map;
+
+public class HttpResponse {
+
+ private Logger log = LoggerFactory.getLogger(getClass());
+ private int status;
+ private Map<String, String> headers = new HashMap<>();
+
+ public void processResponse(String path, HttpResponse response, OutputStream out) throws IOException {
+ String contentType = response.getContentType(path);
+ byte[] body = findBody(contentType, path);
+ DataOutputStream dos = new DataOutputStream(out);
+ responseHeader(dos, body.length, contentType);
+ responseBody(dos, body);
+ }
+
+
+ private void responseHeader(DataOutputStream dos, int lengthOfBodyContent, String contentType) {
+ try {
+ dos.writeBytes("HTTP/1.1 " + status + " " + getStatusCode(status) + "\r\n");
+ dos.writeBytes("Content-Type: " + contentType + "\r\n");
+ dos.writeBytes("Content-Length: " + lengthOfBodyContent + "\r\n");
+
+ for (Map.Entry<String, String> header : headers.entrySet()) {
+ dos.writeBytes(header.getKey() + ": " + header.getValue() + "\r\n");
+ }
+
+ dos.writeBytes("\r\n");
+ } catch (IOException e) {
+ log.error(e.getMessage());
+ }
+ }
+
+ private void responseBody(DataOutputStream dos, byte[] body) {
+ try {
+ dos.write(body, 0, body.length);
+ dos.flush();
+ } catch (IOException e) {
+ log.error(e.getMessage());
+ }
+ }
+
+ private String getContentType(String path) {
+ return ContentType.findContentType(path).getValue();
+ }
+
+ private byte[] findBody(String contentType, String path) throws IOException {
+ return Files.readAllBytes(new File(ResponseBody.findResponseBody(contentType).getPath() + path).toPath());
+ }
+
+ public void setStatus(int status) {
+ this.status = status;
+ }
+
+ public void setHeader(String name, String value) {
+ headers.put(name, value);
+ }
+
+ private String getStatusCode(int status) {
+ if (status == HttpStatus.MOVED_TEMPORARILY.getValue()) {
+ return HttpStatus.MOVED_TEMPORARILY.getReason();
+ }
+
+ return HttpStatus.OK.getReason();
+ }
+
+ public String getResponse() {
+ return headers.getOrDefault("Location", "");
+ }
+} | Java | status์ header๋ก ๋๋์ด ์ ์ฅํ๋ ๊ฒ ์ข๋ค์!! |
@@ -0,0 +1,81 @@
+package util;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.DataOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.util.HashMap;
+import java.util.Map;
+
+public class HttpResponse {
+
+ private Logger log = LoggerFactory.getLogger(getClass());
+ private int status;
+ private Map<String, String> headers = new HashMap<>();
+
+ public void processResponse(String path, HttpResponse response, OutputStream out) throws IOException {
+ String contentType = response.getContentType(path);
+ byte[] body = findBody(contentType, path);
+ DataOutputStream dos = new DataOutputStream(out);
+ responseHeader(dos, body.length, contentType);
+ responseBody(dos, body);
+ }
+
+
+ private void responseHeader(DataOutputStream dos, int lengthOfBodyContent, String contentType) {
+ try {
+ dos.writeBytes("HTTP/1.1 " + status + " " + getStatusCode(status) + "\r\n");
+ dos.writeBytes("Content-Type: " + contentType + "\r\n");
+ dos.writeBytes("Content-Length: " + lengthOfBodyContent + "\r\n");
+
+ for (Map.Entry<String, String> header : headers.entrySet()) {
+ dos.writeBytes(header.getKey() + ": " + header.getValue() + "\r\n");
+ }
+
+ dos.writeBytes("\r\n");
+ } catch (IOException e) {
+ log.error(e.getMessage());
+ }
+ }
+
+ private void responseBody(DataOutputStream dos, byte[] body) {
+ try {
+ dos.write(body, 0, body.length);
+ dos.flush();
+ } catch (IOException e) {
+ log.error(e.getMessage());
+ }
+ }
+
+ private String getContentType(String path) {
+ return ContentType.findContentType(path).getValue();
+ }
+
+ private byte[] findBody(String contentType, String path) throws IOException {
+ return Files.readAllBytes(new File(ResponseBody.findResponseBody(contentType).getPath() + path).toPath());
+ }
+
+ public void setStatus(int status) {
+ this.status = status;
+ }
+
+ public void setHeader(String name, String value) {
+ headers.put(name, value);
+ }
+
+ private String getStatusCode(int status) {
+ if (status == HttpStatus.MOVED_TEMPORARILY.getValue()) {
+ return HttpStatus.MOVED_TEMPORARILY.getReason();
+ }
+
+ return HttpStatus.OK.getReason();
+ }
+
+ public String getResponse() {
+ return headers.getOrDefault("Location", "");
+ }
+} | Java | ์ด ํด๋์ค์์ ์ ์ฒด์ ์ผ๋ก ์ ๊ฐ ๊ตฌํํ๊ณ ์ถ์ ๋ถ๋ถ๋ค์ ์ ๋๋์ด์ฃผ์ ๊ฒ ๊ฐ์์! ๋ง์ด ๋ฐฐ์ ์ต๋๋ค |
@@ -0,0 +1,81 @@
+package util;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.DataOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.util.HashMap;
+import java.util.Map;
+
+public class HttpResponse {
+
+ private Logger log = LoggerFactory.getLogger(getClass());
+ private int status;
+ private Map<String, String> headers = new HashMap<>();
+
+ public void processResponse(String path, HttpResponse response, OutputStream out) throws IOException {
+ String contentType = response.getContentType(path);
+ byte[] body = findBody(contentType, path);
+ DataOutputStream dos = new DataOutputStream(out);
+ responseHeader(dos, body.length, contentType);
+ responseBody(dos, body);
+ }
+
+
+ private void responseHeader(DataOutputStream dos, int lengthOfBodyContent, String contentType) {
+ try {
+ dos.writeBytes("HTTP/1.1 " + status + " " + getStatusCode(status) + "\r\n");
+ dos.writeBytes("Content-Type: " + contentType + "\r\n");
+ dos.writeBytes("Content-Length: " + lengthOfBodyContent + "\r\n");
+
+ for (Map.Entry<String, String> header : headers.entrySet()) {
+ dos.writeBytes(header.getKey() + ": " + header.getValue() + "\r\n");
+ }
+
+ dos.writeBytes("\r\n");
+ } catch (IOException e) {
+ log.error(e.getMessage());
+ }
+ }
+
+ private void responseBody(DataOutputStream dos, byte[] body) {
+ try {
+ dos.write(body, 0, body.length);
+ dos.flush();
+ } catch (IOException e) {
+ log.error(e.getMessage());
+ }
+ }
+
+ private String getContentType(String path) {
+ return ContentType.findContentType(path).getValue();
+ }
+
+ private byte[] findBody(String contentType, String path) throws IOException {
+ return Files.readAllBytes(new File(ResponseBody.findResponseBody(contentType).getPath() + path).toPath());
+ }
+
+ public void setStatus(int status) {
+ this.status = status;
+ }
+
+ public void setHeader(String name, String value) {
+ headers.put(name, value);
+ }
+
+ private String getStatusCode(int status) {
+ if (status == HttpStatus.MOVED_TEMPORARILY.getValue()) {
+ return HttpStatus.MOVED_TEMPORARILY.getReason();
+ }
+
+ return HttpStatus.OK.getReason();
+ }
+
+ public String getResponse() {
+ return headers.getOrDefault("Location", "");
+ }
+} | Java | `headers` ๋ฅผ ์ด์ฉํด์ ๋ ๋ฆฌํฉํ ๋ง ํ ์ ์์ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,56 @@
+package util;
+
+public class HttpRequest {
+
+ private String method;
+ private String url;
+ private String queryString;
+
+ public HttpRequest(String line) {
+ String[] splitHeader = line.split(" ");
+ // uriPath = ์ ์ฒด uri (์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ ๋ถ๋ฆฌ ์ )
+ String uriPath = getURIPath(splitHeader);
+
+ // ์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ ๋ถ๋ฆฌ ํ url
+ this.url = getPath(uriPath);
+ this.method = splitHeader[0];
+ this.queryString = getQueryParameters(uriPath);
+ }
+
+ public String getMethod() {
+ return method;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public String getQueryString() {
+ return queryString;
+ }
+
+ @Override
+ public String toString() {
+ return "HttpRequest{" +
+ "method='" + method + '\'' +
+ ", url='" + url + '\'' +
+ ", queryString='" + queryString + '\'' +
+ '}';
+ }
+
+ private String getURIPath(String[] splitHeader) {
+ return splitHeader[1];
+ }
+
+ private String getPath(String uriPath) {
+ return uriPath.split("\\?")[0];
+ }
+
+ private String getQueryParameters(String uriPath) {
+ String[] split = uriPath.split("\\?");
+ if (split.length > 1) {
+ return split[1];
+ }
+ return "";
+ }
+} | Java | inline์ผ๋ก ์ค์ฌ๋ณด๋ ๊ฑด์ด๋จ๊น์? ์๋ฏธ๋ฅผ ๋๋ฌ๋ด๋ ์ง์ญ๋ณ์๊ฐ ์๋๋ผ๋ฉด ์๋ตํ๋ ํธ์ด ๊น๋ํ ๊ฑฐ๊ฐ์์. |
@@ -0,0 +1,45 @@
+package controller;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import service.UserJoinService;
+import util.HttpRequest;
+import util.HttpResponse;
+
+public class UserController {
+ private final String HTTP_GET = "GET";
+ private final String JOIN_FORM = "/user/form.html";
+ private final String CREATE_USER_URL = "/user/create";
+ private UserJoinService userJoinService;
+ private Logger log = LoggerFactory.getLogger(getClass());
+
+ public UserController(UserJoinService userJoinService) {
+ this.userJoinService = userJoinService;
+ }
+
+ // TODO : ์๋ฌํ์ด์ง ์์ฑ, ํ์๊ฐ์
๊ฒ์ฆ
+ public String process(HttpRequest request, HttpResponse response) {
+ // GET ์์ฒญ์ธ ๊ฒฝ์ฐ ๋ถ๋ฆฌ
+ if (request.getMethod().equals(HTTP_GET)) {
+ // ํ์ ๊ฐ์
ํผ ๋ณด์ฌ์ฃผ๊ธฐ
+ if (request.getUrl().equals(JOIN_FORM)) {
+ return JOIN_FORM;
+ }
+ // ํ์๊ฐ์
์ผ ๊ฒฝ์ฐ
+ if (request.getUrl().equals(CREATE_USER_URL)) {
+ return addUser(request.getQueryString(), response);
+ }
+ }
+
+ return "/error";
+ }
+
+ private String addUser(String queryParameters, HttpResponse response) {
+ userJoinService.addUser(queryParameters);
+
+ response.setStatus(302);
+ response.setHeader("Location", "/index.html");
+ return response.getResponse();
+ }
+
+} | Java | ์์๊ฐ ๋ง์์ง๋ฉด ์ข ํท๊ฐ๋ฆด๊ฑฐ๊ฐ์์, ์๊ทธ๋์ฒ์ ๊ท์น๊ฐ์๊ฒ ์์ผ๋ฉด ์ข๊ฒ ๋ค์ |
@@ -29,14 +29,14 @@ public Game findMatchTypeById(Integer matchId) {
"FROM matches WHERE id = ?";
return jdbcTemplate.queryForObject(SQL, new Object[]{matchId},
(rs, rowNum) -> Game.builder()
- .id(rs.getInt("id"))
- .awayTeam(rs.getInt("away_team"))
- .homeTeam(rs.getInt("home_team"))
- .awayUser(rs.getInt("away_user"))
- .homeUser(rs.getInt("home_user"))
- .inning(rs.getInt("inning"))
- .isFirsthalf(rs.getBoolean("is_firsthalf"))
- .build());
+ .id(rs.getInt("id"))
+ .awayTeam(rs.getInt("away_team"))
+ .homeTeam(rs.getInt("home_team"))
+ .awayUser(rs.getInt("away_user"))
+ .homeUser(rs.getInt("home_user"))
+ .inning(rs.getInt("inning"))
+ .isFirsthalf(rs.getBoolean("is_firsthalf"))
+ .build());
}
public Game findGameById(Integer gameId) {
@@ -58,10 +58,10 @@ public Integer insertNewGame(Game matchType) {
String SQL = "INSERT INTO game (away_team, home_Team, inning, is_firsthalf) " +
"VALUES (:awayTeam, :homeTeam, :inning, :isFirsthalf)";
SqlParameterSource namedParameters = new MapSqlParameterSource()
- .addValue("awayTeam", matchType.getAwayTeam())
- .addValue("homeTeam", matchType.getHomeTeam())
- .addValue("inning", matchType.getInning())
- .addValue("isFirsthalf", matchType.isFirsthalf());
+ .addValue("awayTeam", matchType.getAwayTeam())
+ .addValue("homeTeam", matchType.getHomeTeam())
+ .addValue("inning", matchType.getInning())
+ .addValue("isFirsthalf", matchType.isFirsthalf());
KeyHolder keyHolder = new GeneratedKeyHolder();
Integer generatedGameId = namedParameterJdbcTemplate.update(SQL, namedParameters, keyHolder, new String[]{"generatedGameId"});
return keyHolder.getKey().intValue();
@@ -75,11 +75,11 @@ public List<Integer> findAllGameIds() {
public List<Game> findAllMatches() {
String SQL = "SELECT id, away_team, home_team, away_user, home_user FROM matches";
return jdbcTemplate.query(SQL, (rs, rowNum) -> Game.builder()
- .id(rs.getInt("id"))
- .awayTeam(rs.getInt("away_team"))
- .homeTeam(rs.getInt("home_team"))
- .awayUser(rs.getInt("away_user"))
- .homeUser(rs.getInt("home_user"))
- .build());
+ .id(rs.getInt("id"))
+ .awayTeam(rs.getInt("away_team"))
+ .homeTeam(rs.getInt("home_team"))
+ .awayUser(rs.getInt("away_user"))
+ .homeUser(rs.getInt("home_user"))
+ .build());
}
} | Java | ์กฐ๊ธ์ด๋ผ๋ ๋ ๋ณด๊ธฐ์ข์ ์ฝ๋๋ฅผ ์์ฑํ๊ธฐ ์ํ ๋
ธ๋ ฅ์ธ๊ฐ์. ๐ |
@@ -1,13 +1,16 @@
package kr.codesquad.baseball.dto;
-import lombok.AllArgsConstructor;
import lombok.Getter;
-import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter @Setter
-@AllArgsConstructor @NoArgsConstructor
public class GameInitializingRequestDto {
private Integer matchId;
+
+ public GameInitializingRequestDto() {}
+
+ public GameInitializingRequestDto(Integer matchId) {
+ this.matchId = matchId;
+ }
} | Java | Lombok ์ฌ์ฉ์ ๋ํด์ ์กฐ๊ธ ๊บผ๋ ค์ง์๋ ๋ฉด์ด ์๋ ๊ฒ ๊ฐ์๋ฐ lombok ์ด์ ์ฐ์
๋ ๊ด์ฐฎ์์.
๋ค๋ง ๊ณตํต์ ์ผ๋ก ์ฃผ์ํด์ผ ํ ์ฌํญ๋ค์ด ์๋๋ฐ, ์๋ ๋งํฌ๋ฅผ ์ฐธ๊ณ ํด ์ฃผ์ธ์.
https://kwonnam.pe.kr/wiki/java/lombok/pitfall |
@@ -1,13 +1,10 @@
package kr.codesquad.baseball.dto.teamVO;
import com.fasterxml.jackson.annotation.JsonIgnore;
-import com.fasterxml.jackson.annotation.JsonProperty;
-import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@Getter @Setter
-@AllArgsConstructor
public class TeamVO {
@JsonIgnore
@@ -19,4 +16,13 @@ public class TeamVO {
@JsonIgnore
private int score;
+
+ public TeamVO() {}
+
+ public TeamVO(Integer teamId, String teamName, int totalScore, int score) {
+ this.teamId = teamId;
+ this.teamName = teamName;
+ this.totalScore = totalScore;
+ this.score = score;
+ }
} | Java | `VO`, `DTO`, ๊ทธ๋ฆฌ๊ณ ๋ชจ๋ธ ํด๋์ค๋ฅผ ์ด๋ค ๊ธฐ์ค์ผ๋ก ๊ตฌ๋ถํ์
จ๋์? |
@@ -1,13 +1,16 @@
package kr.codesquad.baseball.dto;
-import lombok.AllArgsConstructor;
import lombok.Getter;
-import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter @Setter
-@AllArgsConstructor @NoArgsConstructor
public class GameInitializingRequestDto {
private Integer matchId;
+
+ public GameInitializingRequestDto() {}
+
+ public GameInitializingRequestDto(Integer matchId) {
+ this.matchId = matchId;
+ }
} | Java | ์ด์ ๋ถํฐ ๋กฌ๋ณต์ ์๋ฌด ์๊ฐ ์์ด ๊ธฐ๊ณ์ ์ผ๋ก ์ฌ์ฉ ํ๋๊ฑฐ ๊ฐ์ต๋๋ค. ์ง๋ ํ๋ก์ ํธ์ ๋น๋๋ฅผ ์จ๋ณด๋ฉด์ ๋๋์ฑ ๋กฌ๋ณต ์์ด ๊ตฌํ์ ํด๋ด์ผ๊ฒ ๋ค๋ ์๊ฐ์ด ๋ค์ด์ ํ์ด์๊ฒ ์ฐ์ง ๋ง์๊ณ ์ ์ํ๊ณ , ์ด๋ฒ ํ๋ก์ ํธ์๋ ํด๋์ค์ ๋น๋๋ฅผ ์ง์ ๋ง๋ค์ด๋ณด๊ณ ์๋๋ฐ ๊ณต๋ถ๊ฐ ๋ง์ด ๋๊ณ ์๋ค์.
์๋ ค์ฃผ์ ์ฃผ์์ฌํญ ๋งํฌ๋ ์ฝ์ด ๋ดค๋๋ฐ ๋ชจ๋ฅด๊ณ ์ด๊ฒ ์ฐธ ๋ง์๋ค๋ ์๊ฐ์ด ๋๋ค์! ๋ค์ ํ๋ก์ ํธ๋ถํฐ ์ ์ํ๋ฉฐ ์ฌ์ฉ ํ๊ฒ ์ต๋๋ค. ์กฐ์ธ ํด์ฃผ์
์ ๊ฐ์ฌํฉ๋๋ค. |
@@ -1,13 +1,10 @@
package kr.codesquad.baseball.dto.teamVO;
import com.fasterxml.jackson.annotation.JsonIgnore;
-import com.fasterxml.jackson.annotation.JsonProperty;
-import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@Getter @Setter
-@AllArgsConstructor
public class TeamVO {
@JsonIgnore
@@ -19,4 +16,13 @@ public class TeamVO {
@JsonIgnore
private int score;
+
+ public TeamVO() {}
+
+ public TeamVO(Integer teamId, String teamName, int totalScore, int score) {
+ this.teamId = teamId;
+ this.teamName = teamName;
+ this.totalScore = totalScore;
+ this.score = score;
+ }
} | Java | ๋ชจ๋ธ ํด๋์ค๋ DB์ ์ํฐํฐ์ ์ง์ ๋์๋๋ ํด๋์ค๋ผ ์๊ฐ ํ๊ณ , VO๋ DB์ ์ฌ๋ฌ ์ํฐํฐ ๋ฐ์ดํฐ๋ฅผ DTO์ ์๋ง๊ฒ ๊ฐ๊ณตํ ์ต์ ๋จ์(DTO์ ๋ถ๋ถ ์งํฉ), DTO๋ ํด๋ผ์ด์ธํธ์ ํต์ ์ ํ๋ ์ ์ ์์ ์ฌ์ฉ๋๋ ์ต์ข
๋ฐ์ดํฐ ํด๋์ค๋ผ๋ ๊ธฐ์ค์ ์ธ์ฐ๊ณ ์ฌ์ฉ์ ํ์์ต๋๋ค.
๋ฐฑ์๋ ์๊ตฌ ์ฌํญ์ธ(์ต์
) ํ, ์ ์ ๋ฐ์ดํฐ ๊ด๋ฆฌ ํด์ ์ผ๋์ ๋๊ณ ๋ถ๋ฅ๋ฅผ ํ๋๊ฑด๋ฐ, ๋ก์ง์ด ๋ณต์กํด์ง๋ค ๋ณด๋ VO์ ๋ชจ๋ธ ์ฌ์ด์ ๊ฒฝ๊ณ๊ฐ ๋ง์ด ๋ชจํธํด์ง๊ฑฐ ๊ฐ์ต๋๋คใ
ใ
์ด๋ฐ ๊ฒฝ์ฐ์ VO๋ผ๋ ์ฝ์ด๋ฅผ ์ฌ์ฉํ๋๊ฒ ๋ง๋๊ฑด์ง ์ ๋งคํ ์ ์ด ์์๋๋ฐ, ์๋ฌด๋๋ ๋ ๊ณต๋ถํ๊ณ ์๊ฐ์ ํด๋ด์ผ ํ ๊ฑฐ ๊ฐ์ต๋๋ค. ์กฐ์ธ ํด์ฃผ์ ๊ฒ์ฒ๋ผ ํ์ต์ ๋ ํด๋ณด๊ฒ ์ต๋๋ค! |
@@ -0,0 +1,48 @@
+/* http://meyerweb.com/eric/tools/css/reset/
+ v2.0 | 20110126
+ License: none (public domain)
+*/
+
+html, body, div, span, applet, object, iframe,
+h1, h2, h3, h4, h5, h6, p, blockquote, pre,
+a, abbr, acronym, address, big, cite, code,
+del, dfn, em, img, ins, kbd, q, s, samp,
+small, strike, strong, sub, sup, tt, var,
+b, u, i, center,
+dl, dt, dd, ol, ul, li,
+fieldset, form, label, legend,
+table, caption, tbody, tfoot, thead, tr, th, td,
+article, aside, canvas, details, embed,
+figure, figcaption, footer, header, hgroup,
+menu, nav, output, ruby, section, summary,
+time, mark, audio, video {
+ margin: 0;
+ padding: 0;
+ border: 0;
+ font-size: 100%;
+ font: inherit;
+ vertical-align: baseline;
+}
+/* HTML5 display-role reset for older browsers */
+article, aside, details, figcaption, figure,
+footer, header, hgroup, menu, nav, section {
+ display: block;
+}
+body {
+ line-height: 1;
+}
+ol, ul {
+ list-style: none;
+}
+blockquote, q {
+ quotes: none;
+}
+blockquote:before, blockquote:after,
+q:before, q:after {
+ content: '';
+ content: none;
+}
+table {
+ border-collapse: collapse;
+ border-spacing: 0;
+} | Unknown | css ๋ฆฌ์
์๊ณ ์์๋๋ฐ ๋ฆฌ๋ง์ธ๋ํ๊ณ ๊ฐ๋๋ค! |
@@ -1,9 +1,10 @@
import { useState } from "react";
-import Input from "../components/Input";
import InputBox from "../components/InputBox";
-import validation from "../utils/validation";
+import InputCheckBox from "../components/InputCheckBox";
+import validateFormInfos from "../utils/validation";
import checking from "../utils/checking";
import { useNavigate } from "react-router-dom";
+import './Signup.css';
function Signup() {
const [infos, setInfos] = useState({
@@ -14,8 +15,8 @@ function Signup() {
userName: "",
recommender: "",
allTerms: false,
- term1: false,
- term2: false,
+ term: false,
+ privacy: false,
marketing: false
});
@@ -38,7 +39,7 @@ function Signup() {
const checkedList = ["email", "phone", "userName", "recommender"]
const {id, value} = e.currentTarget;
setInfos({...infos, [id]: value});
- if (validationList.includes(id) && !validation({id, value, isValidInfos, setIsValidInfos})) {
+ if (validationList.includes(id) && !validateFormInfos({id, value, isValidInfos, setIsValidInfos})) {
if (checkedList.includes(id))
setIsCheckedInfos({...isCheckedInfos, [id]: false})
return;
@@ -49,153 +50,166 @@ function Signup() {
checking({id, value, isCheckedInfos, setIsCheckedInfos})
}
- const handleChangeInputBox = (e : React.FormEvent<HTMLInputElement>) => {
+ const handleChangeInputCheckBox = (e : React.FormEvent<HTMLInputElement>) => {
const {id, checked} = e.currentTarget;
if (id === "allTerms") {
- setInfos({...infos, allTerms: checked, term1: checked, term2: checked, marketing: checked});
+ setInfos({...infos, allTerms: checked, term: checked, privacy: checked, marketing: checked});
} else {
setInfos({...infos, [id]: checked})
if (!checked) {
setInfos({...infos, [id]: false, allTerms: false})
- } else if ((infos.term1 && infos.term2) || (infos.term2 && infos.marketing) || (infos.term1 && infos.marketing)) {
+ } else if ((infos.term && infos.privacy) || (infos.privacy && infos.marketing) || (infos.term && infos.marketing)) {
setInfos({...infos, [id]: true, allTerms: true})
}
}
}
const navigate = useNavigate();
- const handleSubmit = (e : any) => {
+ const handleSubmit = (e : React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
navigate("/greeting");
}
return(
- <form onSubmit={handleSubmit}>
- <div>
+ <div className="signup">
+ <div className="signup__title">
+ ํ์๊ฐ์
+ </div>
+ <div className="signup__msg">
* ํ์๋ ํญ๋ชฉ์ ํ์๋ก ์
๋ ฅํด์ผํฉ๋๋ค
</div>
- <div>
- ์ด๋ฉ์ผ*
- <div>
- <Input
+ <form className="signup__form" onSubmit={handleSubmit}>
+ <div className="signup__form__content">
+ <InputBox
type="text"
id="email"
value={infos.email}
onChange={handleChange}
+ label="์ด๋ฉ์ผ"
+ required={true}
/>
- {isValidInfos.email ? isCheckedInfos.email ? "์ฌ์ฉ ๊ฐ๋ฅํ ์ด๋ฉ์ผ์
๋๋ค" : "์ด๋ฏธ ์ฌ์ฉ์ค์ธ ์ด๋ฉ์ผ์
๋๋ค" : "์ ํจํ์ง ์์ ์ด๋ฉ์ผ์
๋๋ค"}
+ <div className="signup__form__content__msg">
+ {isValidInfos.email ? isCheckedInfos.email ? "์ฌ์ฉ ๊ฐ๋ฅํ ์ด๋ฉ์ผ์
๋๋ค" : "์ด๋ฏธ ์ฌ์ฉ์ค์ธ ์ด๋ฉ์ผ์
๋๋ค" : "์ ํจํ์ง ์์ ์ด๋ฉ์ผ์
๋๋ค"}
+ </div>
</div>
- </div>
- <div>
- ์ ํ๋ฒํธ*
- <div>
- <Input
+ <div className="signup__form__content">
+ <InputBox
type="text"
id="phone"
value={infos.phone}
onChange={handleChange}
+ label="์ ํ๋ฒํธ"
+ required={true}
/>
- {isValidInfos.phone ? isCheckedInfos.phone? "์ฌ์ฉ ๊ฐ๋ฅํ ์ ํ๋ฒํธ์
๋๋ค" : "์ด๋ฏธ ์ฌ์ฉ์ค์ธ ์ ํ๋ฒํธ์
๋๋ค" : "์ ํจํ์ง ์์ ์ ํ๋ฒํธ์
๋๋ค"}
+ <div className="signup__form__content__msg">
+ {isValidInfos.phone ? isCheckedInfos.phone? "์ฌ์ฉ ๊ฐ๋ฅํ ์ ํ๋ฒํธ์
๋๋ค" : "์ด๋ฏธ ์ฌ์ฉ์ค์ธ ์ ํ๋ฒํธ์
๋๋ค" : "์ ํจํ์ง ์์ ์ ํ๋ฒํธ์
๋๋ค"}
+ </div>
</div>
- </div>
- <div>
- ๋น๋ฐ๋ฒํธ* (๋น๋ฐ๋ฒํธ๋ 8์ ์ด์, ์๋ฌธ ๋,์๋ฌธ์, ์ซ์๋ฅผ ํฌํจํด์ผํฉ๋๋ค)
- <div>
- <Input
+ <div className="signup__form__content">
+ <InputBox
type="password"
id="password"
value={infos.password}
onChange={handleChange}
+ label="๋น๋ฐ๋ฒํธ(๋น๋ฐ๋ฒํธ๋ 8์ ์ด์, ์๋ฌธ ๋,์๋ฌธ์, ์ซ์๋ฅผ ํฌํจํด์ผํฉ๋๋ค)"
+ required={true}
/>
- {isValidInfos.password ? "" : "๋น๋ฐ๋ฒํธ ํ์์ ๋ง์ง ์์ต๋๋ค"}
+ <div className="signup__form__content__msg">
+ {isValidInfos.password ? "" : "๋น๋ฐ๋ฒํธ ํ์์ ๋ง์ง ์์ต๋๋ค"}
+ </div>
</div>
- ๋น๋ฐ๋ฒํธ ํ์ธ*
- <div>
- <Input
+ <div className="signup__form__content">
+ <InputBox
type="password"
id="repassword"
value={infos.repassword}
onChange={handleChange}
+ label="๋น๋ฐ๋ฒํธ ํ์ธ"
+ required={true}
/>
- {isCheckedInfos.password ? "" : "๋น๋ฐ๋ฒํธ๊ฐ ์ผ์นํ์ง ์์ต๋๋ค"}
+ <div className="signup__form__content__msg">
+ {isCheckedInfos.password ? "" : "๋น๋ฐ๋ฒํธ๊ฐ ์ผ์นํ์ง ์์ต๋๋ค"}
+ </div>
</div>
- </div>
- <div>
- ์ ์ ๋ค์*
- <div>
- <Input
+ <div className="signup__form__content">
+ <InputBox
type="text"
id="userName"
value={infos.userName}
onChange={handleChange}
+ label="์ ์ ๋ค์"
+ required={true}
/>
- {isCheckedInfos.userName ? "์ฌ์ฉ ๊ฐ๋ฅํ ์ ์ ๋ค์์
๋๋ค" : "์ฌ์ฉ์ค์ธ ์ ์ ๋ค์์
๋๋ค"}
+ <div className="signup__form__content__msg">
+ {isCheckedInfos.userName ? "์ฌ์ฉ ๊ฐ๋ฅํ ์ ์ ๋ค์์
๋๋ค" : "์ฌ์ฉ์ค์ธ ์ ์ ๋ค์์
๋๋ค"}
+ </div>
</div>
- </div>
- <div>
- ์ถ์ฒ์ธ ์ ์ ๋ค์
- <div>
- <Input
+ <div className="signup__form__content">
+ <InputBox
type="text"
id="recommender"
value={infos.recommender}
onChange={handleChange}
+ label="์ถ์ฒ์ธ ์ ์ ๋ค์"
+ required={false}
/>
- {infos.recommender && (isCheckedInfos.recommender ? "์ถ์ฒ์ธ์ด ํ์ธ๋์์ต๋๋ค" : "์ถ์ฒ์ธ์ด ํ์ธ๋์ง ์์์ต๋๋ค")}
- </div>
- </div>
- <div>
- ์ฝ๊ด ๋ฐ ๋ง์ผํ
๋์
- <div>
- ๋ชจ๋ ๋์
- <InputBox
- id="allTerms"
- checked={infos.allTerms}
- onChange={handleChangeInputBox}
- />
-
- </div>
- <div>
- ์ฝ๊ด 1*
- <InputBox
- id="term1"
- checked={infos.term1}
- onChange={handleChangeInputBox}
- />
+ <div className="signup__form__content__msg">
+ {infos.recommender && (isCheckedInfos.recommender ? "์ถ์ฒ์ธ์ด ํ์ธ๋์์ต๋๋ค" : "์ถ์ฒ์ธ์ด ํ์ธ๋์ง ์์์ต๋๋ค")}
+ </div>
</div>
- <div>
- ์ฝ๊ด2*
- <InputBox
- id="term2"
- checked={infos.term2}
- onChange={handleChangeInputBox}
- />
+ <div className="signup__form__checkbox">
+ <div className="signup__form__checkbox__title">
+ ์ฝ๊ด ๋ฐ ๋ง์ผํ
๋์
+ </div>
+ <div>
+ <InputCheckBox
+ id="allTerms"
+ checked={infos.allTerms}
+ onChange={handleChangeInputCheckBox}
+ label="๋ชจ๋ ๋์"
+ required={false}
+ />
+ <InputCheckBox
+ id="term"
+ checked={infos.term}
+ onChange={handleChangeInputCheckBox}
+ label="์ฝ๊ด"
+ required={true}
+ />
+ <InputCheckBox
+ id="privacy"
+ checked={infos.privacy}
+ onChange={handleChangeInputCheckBox}
+ label="๊ฐ์ธ์ ๋ณดํ์ฉ๋์"
+ required={true}
+ />
+ <InputCheckBox
+ id="marketing"
+ checked={infos.marketing}
+ onChange={handleChangeInputCheckBox}
+ label="๋ง์ผํ
๋์"
+ required={false}
+ />
+ </div>
</div>
- <div>
- ๋ง์ผํ
๋์
- <InputBox
- id="marketing"
- checked={infos.marketing}
- onChange={handleChangeInputBox}
+ <div className="signup__form__submit">
+ <input
+ className="signup__form__submit__input"
+ type="submit"
+ value="์ ์ถ"
+ disabled={
+ isCheckedInfos.email && isCheckedInfos.phone
+ && isValidInfos.password && isCheckedInfos.password
+ && isCheckedInfos.userName
+ && ((infos.recommender && isCheckedInfos.recommender) || !infos.recommender)
+ && infos.term && infos.privacy
+ ? false : true
+ }
/>
</div>
- </div>
- <div>
- <input
- type="submit"
- value="์ ์ถ"
- disabled={
- isCheckedInfos.email && isCheckedInfos.phone
- && isValidInfos.password && isCheckedInfos.password
- && isCheckedInfos.userName
- && ((infos.recommender && isCheckedInfos.recommender) || !infos.recommender)
- && infos.term1 && infos.term2
- ? false : true
- }
- />
- </div>
- </form>
+ </form>
+ </div>
)
}
| Unknown | ๋ณ์๋ช
๋ฐ๊พธ์ ๊ฑฐ ๊ตฟ๊ตฟ |
@@ -1,19 +1,28 @@
+import './InputBox.css';
+
type InputBoxProps = {
+ type: string;
id: string;
- checked: boolean;
- onChange: any;
+ value: string;
+ onChange: (e : React.FormEvent<HTMLInputElement>) => void;
+ label: string;
+ required: boolean;
}
-const InputBox = ({id, checked, onChange}: InputBoxProps) => {
+const InputBox = ({type, id, value, onChange, label, required}: InputBoxProps) => {
return (
- <>
+ <div className='inputBox'>
+ <div className={required ? 'inputBox__title inputBox__title__required' : 'inputBox__title'}>
+ {label}{required && '*'}
+ </div>
<input
- type="checkbox"
+ className='inputBox__input'
+ type={type}
id={id}
- checked={checked}
+ value={value}
onChange={onChange}
/>
- </>
+ </div>
)
}
| Unknown | ์ปดํฌ๋ํธ ์ด๋ฆ์ด InputBox๋๊น checkbox์ฉ input ์์๋ฅผ ์ํ ์ปดํฌ๋ํธ ๊ฐ์๋ฐ, type props๋ฅผ ์ถ๊ฐํ๊ณ checked ์์ฑ ๋์ value ์์ฑ์ผ๋ก ๋ณ๊ฒฝํ์ ์ด์ ๊ฐ ์์๊น์? |
@@ -1,19 +1,28 @@
+import './InputBox.css';
+
type InputBoxProps = {
+ type: string;
id: string;
- checked: boolean;
- onChange: any;
+ value: string;
+ onChange: (e : React.FormEvent<HTMLInputElement>) => void;
+ label: string;
+ required: boolean;
}
-const InputBox = ({id, checked, onChange}: InputBoxProps) => {
+const InputBox = ({type, id, value, onChange, label, required}: InputBoxProps) => {
return (
- <>
+ <div className='inputBox'>
+ <div className={required ? 'inputBox__title inputBox__title__required' : 'inputBox__title'}>
+ {label}{required && '*'}
+ </div>
<input
- type="checkbox"
+ className='inputBox__input'
+ type={type}
id={id}
- checked={checked}
+ value={value}
onChange={onChange}
/>
- </>
+ </div>
)
}
| Unknown | ์! ๋ฐ์ InputCheckBox๊ฐ ๋ฐ๋ก ์๊ณ ์๋์ Input์ด InputBox๋ก ๋ณ๊ฒฝ๋๊ฑฐ์๊ตฐ์. ์ ๋ ์์ ์ ๊ทธ๋๋ก Input๊ณผ InputCheckBox๊ฐ ๋ ๋์๋ณด์ฌ์..! |
@@ -1,9 +1,10 @@
import { useState } from "react";
-import Input from "../components/Input";
import InputBox from "../components/InputBox";
-import validation from "../utils/validation";
+import InputCheckBox from "../components/InputCheckBox";
+import validateFormInfos from "../utils/validation";
import checking from "../utils/checking";
import { useNavigate } from "react-router-dom";
+import './Signup.css';
function Signup() {
const [infos, setInfos] = useState({
@@ -14,8 +15,8 @@ function Signup() {
userName: "",
recommender: "",
allTerms: false,
- term1: false,
- term2: false,
+ term: false,
+ privacy: false,
marketing: false
});
@@ -38,7 +39,7 @@ function Signup() {
const checkedList = ["email", "phone", "userName", "recommender"]
const {id, value} = e.currentTarget;
setInfos({...infos, [id]: value});
- if (validationList.includes(id) && !validation({id, value, isValidInfos, setIsValidInfos})) {
+ if (validationList.includes(id) && !validateFormInfos({id, value, isValidInfos, setIsValidInfos})) {
if (checkedList.includes(id))
setIsCheckedInfos({...isCheckedInfos, [id]: false})
return;
@@ -49,153 +50,166 @@ function Signup() {
checking({id, value, isCheckedInfos, setIsCheckedInfos})
}
- const handleChangeInputBox = (e : React.FormEvent<HTMLInputElement>) => {
+ const handleChangeInputCheckBox = (e : React.FormEvent<HTMLInputElement>) => {
const {id, checked} = e.currentTarget;
if (id === "allTerms") {
- setInfos({...infos, allTerms: checked, term1: checked, term2: checked, marketing: checked});
+ setInfos({...infos, allTerms: checked, term: checked, privacy: checked, marketing: checked});
} else {
setInfos({...infos, [id]: checked})
if (!checked) {
setInfos({...infos, [id]: false, allTerms: false})
- } else if ((infos.term1 && infos.term2) || (infos.term2 && infos.marketing) || (infos.term1 && infos.marketing)) {
+ } else if ((infos.term && infos.privacy) || (infos.privacy && infos.marketing) || (infos.term && infos.marketing)) {
setInfos({...infos, [id]: true, allTerms: true})
}
}
}
const navigate = useNavigate();
- const handleSubmit = (e : any) => {
+ const handleSubmit = (e : React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
navigate("/greeting");
}
return(
- <form onSubmit={handleSubmit}>
- <div>
+ <div className="signup">
+ <div className="signup__title">
+ ํ์๊ฐ์
+ </div>
+ <div className="signup__msg">
* ํ์๋ ํญ๋ชฉ์ ํ์๋ก ์
๋ ฅํด์ผํฉ๋๋ค
</div>
- <div>
- ์ด๋ฉ์ผ*
- <div>
- <Input
+ <form className="signup__form" onSubmit={handleSubmit}>
+ <div className="signup__form__content">
+ <InputBox
type="text"
id="email"
value={infos.email}
onChange={handleChange}
+ label="์ด๋ฉ์ผ"
+ required={true}
/>
- {isValidInfos.email ? isCheckedInfos.email ? "์ฌ์ฉ ๊ฐ๋ฅํ ์ด๋ฉ์ผ์
๋๋ค" : "์ด๋ฏธ ์ฌ์ฉ์ค์ธ ์ด๋ฉ์ผ์
๋๋ค" : "์ ํจํ์ง ์์ ์ด๋ฉ์ผ์
๋๋ค"}
+ <div className="signup__form__content__msg">
+ {isValidInfos.email ? isCheckedInfos.email ? "์ฌ์ฉ ๊ฐ๋ฅํ ์ด๋ฉ์ผ์
๋๋ค" : "์ด๋ฏธ ์ฌ์ฉ์ค์ธ ์ด๋ฉ์ผ์
๋๋ค" : "์ ํจํ์ง ์์ ์ด๋ฉ์ผ์
๋๋ค"}
+ </div>
</div>
- </div>
- <div>
- ์ ํ๋ฒํธ*
- <div>
- <Input
+ <div className="signup__form__content">
+ <InputBox
type="text"
id="phone"
value={infos.phone}
onChange={handleChange}
+ label="์ ํ๋ฒํธ"
+ required={true}
/>
- {isValidInfos.phone ? isCheckedInfos.phone? "์ฌ์ฉ ๊ฐ๋ฅํ ์ ํ๋ฒํธ์
๋๋ค" : "์ด๋ฏธ ์ฌ์ฉ์ค์ธ ์ ํ๋ฒํธ์
๋๋ค" : "์ ํจํ์ง ์์ ์ ํ๋ฒํธ์
๋๋ค"}
+ <div className="signup__form__content__msg">
+ {isValidInfos.phone ? isCheckedInfos.phone? "์ฌ์ฉ ๊ฐ๋ฅํ ์ ํ๋ฒํธ์
๋๋ค" : "์ด๋ฏธ ์ฌ์ฉ์ค์ธ ์ ํ๋ฒํธ์
๋๋ค" : "์ ํจํ์ง ์์ ์ ํ๋ฒํธ์
๋๋ค"}
+ </div>
</div>
- </div>
- <div>
- ๋น๋ฐ๋ฒํธ* (๋น๋ฐ๋ฒํธ๋ 8์ ์ด์, ์๋ฌธ ๋,์๋ฌธ์, ์ซ์๋ฅผ ํฌํจํด์ผํฉ๋๋ค)
- <div>
- <Input
+ <div className="signup__form__content">
+ <InputBox
type="password"
id="password"
value={infos.password}
onChange={handleChange}
+ label="๋น๋ฐ๋ฒํธ(๋น๋ฐ๋ฒํธ๋ 8์ ์ด์, ์๋ฌธ ๋,์๋ฌธ์, ์ซ์๋ฅผ ํฌํจํด์ผํฉ๋๋ค)"
+ required={true}
/>
- {isValidInfos.password ? "" : "๋น๋ฐ๋ฒํธ ํ์์ ๋ง์ง ์์ต๋๋ค"}
+ <div className="signup__form__content__msg">
+ {isValidInfos.password ? "" : "๋น๋ฐ๋ฒํธ ํ์์ ๋ง์ง ์์ต๋๋ค"}
+ </div>
</div>
- ๋น๋ฐ๋ฒํธ ํ์ธ*
- <div>
- <Input
+ <div className="signup__form__content">
+ <InputBox
type="password"
id="repassword"
value={infos.repassword}
onChange={handleChange}
+ label="๋น๋ฐ๋ฒํธ ํ์ธ"
+ required={true}
/>
- {isCheckedInfos.password ? "" : "๋น๋ฐ๋ฒํธ๊ฐ ์ผ์นํ์ง ์์ต๋๋ค"}
+ <div className="signup__form__content__msg">
+ {isCheckedInfos.password ? "" : "๋น๋ฐ๋ฒํธ๊ฐ ์ผ์นํ์ง ์์ต๋๋ค"}
+ </div>
</div>
- </div>
- <div>
- ์ ์ ๋ค์*
- <div>
- <Input
+ <div className="signup__form__content">
+ <InputBox
type="text"
id="userName"
value={infos.userName}
onChange={handleChange}
+ label="์ ์ ๋ค์"
+ required={true}
/>
- {isCheckedInfos.userName ? "์ฌ์ฉ ๊ฐ๋ฅํ ์ ์ ๋ค์์
๋๋ค" : "์ฌ์ฉ์ค์ธ ์ ์ ๋ค์์
๋๋ค"}
+ <div className="signup__form__content__msg">
+ {isCheckedInfos.userName ? "์ฌ์ฉ ๊ฐ๋ฅํ ์ ์ ๋ค์์
๋๋ค" : "์ฌ์ฉ์ค์ธ ์ ์ ๋ค์์
๋๋ค"}
+ </div>
</div>
- </div>
- <div>
- ์ถ์ฒ์ธ ์ ์ ๋ค์
- <div>
- <Input
+ <div className="signup__form__content">
+ <InputBox
type="text"
id="recommender"
value={infos.recommender}
onChange={handleChange}
+ label="์ถ์ฒ์ธ ์ ์ ๋ค์"
+ required={false}
/>
- {infos.recommender && (isCheckedInfos.recommender ? "์ถ์ฒ์ธ์ด ํ์ธ๋์์ต๋๋ค" : "์ถ์ฒ์ธ์ด ํ์ธ๋์ง ์์์ต๋๋ค")}
- </div>
- </div>
- <div>
- ์ฝ๊ด ๋ฐ ๋ง์ผํ
๋์
- <div>
- ๋ชจ๋ ๋์
- <InputBox
- id="allTerms"
- checked={infos.allTerms}
- onChange={handleChangeInputBox}
- />
-
- </div>
- <div>
- ์ฝ๊ด 1*
- <InputBox
- id="term1"
- checked={infos.term1}
- onChange={handleChangeInputBox}
- />
+ <div className="signup__form__content__msg">
+ {infos.recommender && (isCheckedInfos.recommender ? "์ถ์ฒ์ธ์ด ํ์ธ๋์์ต๋๋ค" : "์ถ์ฒ์ธ์ด ํ์ธ๋์ง ์์์ต๋๋ค")}
+ </div>
</div>
- <div>
- ์ฝ๊ด2*
- <InputBox
- id="term2"
- checked={infos.term2}
- onChange={handleChangeInputBox}
- />
+ <div className="signup__form__checkbox">
+ <div className="signup__form__checkbox__title">
+ ์ฝ๊ด ๋ฐ ๋ง์ผํ
๋์
+ </div>
+ <div>
+ <InputCheckBox
+ id="allTerms"
+ checked={infos.allTerms}
+ onChange={handleChangeInputCheckBox}
+ label="๋ชจ๋ ๋์"
+ required={false}
+ />
+ <InputCheckBox
+ id="term"
+ checked={infos.term}
+ onChange={handleChangeInputCheckBox}
+ label="์ฝ๊ด"
+ required={true}
+ />
+ <InputCheckBox
+ id="privacy"
+ checked={infos.privacy}
+ onChange={handleChangeInputCheckBox}
+ label="๊ฐ์ธ์ ๋ณดํ์ฉ๋์"
+ required={true}
+ />
+ <InputCheckBox
+ id="marketing"
+ checked={infos.marketing}
+ onChange={handleChangeInputCheckBox}
+ label="๋ง์ผํ
๋์"
+ required={false}
+ />
+ </div>
</div>
- <div>
- ๋ง์ผํ
๋์
- <InputBox
- id="marketing"
- checked={infos.marketing}
- onChange={handleChangeInputBox}
+ <div className="signup__form__submit">
+ <input
+ className="signup__form__submit__input"
+ type="submit"
+ value="์ ์ถ"
+ disabled={
+ isCheckedInfos.email && isCheckedInfos.phone
+ && isValidInfos.password && isCheckedInfos.password
+ && isCheckedInfos.userName
+ && ((infos.recommender && isCheckedInfos.recommender) || !infos.recommender)
+ && infos.term && infos.privacy
+ ? false : true
+ }
/>
</div>
- </div>
- <div>
- <input
- type="submit"
- value="์ ์ถ"
- disabled={
- isCheckedInfos.email && isCheckedInfos.phone
- && isValidInfos.password && isCheckedInfos.password
- && isCheckedInfos.userName
- && ((infos.recommender && isCheckedInfos.recommender) || !infos.recommender)
- && infos.term1 && infos.term2
- ? false : true
- }
- />
- </div>
- </form>
+ </form>
+ </div>
)
}
| Unknown | ์ ํํ ํ์
์ข์ต๋๋ค~! |
@@ -0,0 +1,28 @@
+import './InputCheckBox.css';
+
+type InputCheckBoxProps = {
+ id: string;
+ checked: boolean;
+ onChange: (e : React.FormEvent<HTMLInputElement>) => void;
+ label?: string;
+ required?: boolean;
+}
+
+const InputCheckBox = ({id, checked, onChange, label, required}: InputCheckBoxProps) => {
+ return (
+ <div className='inputCheckBox'>
+ <input
+ className='inputCheckBox__input'
+ type="checkbox"
+ id={id}
+ checked={checked}
+ onChange={onChange}
+ />
+ <label htmlFor={id} className={required ? 'inputCheckBox__title inputCheckBox__title__required' : 'inputCheckBox__title'}>
+ {label}{required && '*'}
+ </label>
+ </div>
+ )
+}
+
+export default InputCheckBox;
\ No newline at end of file | Unknown | label์ className์ ๊ฒฐ์ ํ๋ ๋ถ๋ถ์ด inputBox์ inputCheckBox์์ ๋ฐ๋ณต๋ฉ๋๋ค. ์ด ๋ถ๋ถ์ ํ์ className๊ณผ ํ๋๊ทธ์ ๋ฐ๋ผ ์ถ๊ฐ์ฌ๋ถ๊ฐ ์ ํด์ง๋ className, ๊ทธ๋ฆฌ๊ณ ํ๋๊ทธ๋ฅผ ์ธ์๋ก ๋ฐ์์ ํด๋์ค ๋ค์์ ๋ฆฌํดํด์ฃผ๋ ํจ์๋ก ๋ฐ๊ฟ๋ณด๋ฉด ์ด๋จ๊น์?
```suggestion
const InputCheckBox = ({id, checked, onChange, label, required}: InputCheckBoxProps) => {
const labelClassName = getClassNameByRequired('inputCheckBox__title', 'inputCheckBox__title__required', required);
return (
<div className='inputCheckBox'>
<input
className='inputCheckBox__input'
type="checkbox"
id={id}
checked={checked}
onChange={onChange}
/>
<label htmlFor={id} className={labelClassName}>
{label}{required && '*'}
</label>
</div>
)
}
```
```js
const getClassNameByRequired = (core:string, suffix:string, required:boolean) => {
return (required) ? `${core} ${suffix}` : `${core}`
}
``` |
@@ -0,0 +1,65 @@
+
+package basball.view;
+
+import basball.baseball.model.GameStatus;
+
+import java.util.Arrays;
+import java.util.Scanner;
+import java.util.regex.Pattern;
+
+public final class InputView {
+
+ private static final String INPUT_NUMBER_MESSAGE = "์ซ์๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์ : ";
+ private static final Scanner sc = new Scanner(System.in);
+
+ public int[] getInputNumber() {
+ System.out.print(INPUT_NUMBER_MESSAGE);
+ String next = sc.next().trim();
+
+ Validator.hasThreeNumber(next);
+
+ return getNumberArray(next);
+ }
+
+ private int[] getNumberArray(String next) {
+ return Arrays.stream(next.split("")).mapToInt(value -> Integer.parseInt(value)).toArray();
+ }
+
+ public GameStatus getRestartInput() {
+ String answer = sc.next();
+ Validator.validateAnswer(answer);
+
+ if (answer.equals("1")) {
+ return GameStatus.RUNNING;
+ }
+ return GameStatus.END;
+ }
+
+ public static class Validator {
+ private static final Pattern PATTERN = Pattern.compile("[1-9]{3}");
+
+ public static void hasThreeNumber(String next) {
+
+ if (!PATTERN.matcher(next).matches()) {
+ throw new IllegalArgumentException("์๋ก ๋ค๋ฅธ 3์๋ฆฌ ์ซ์๋ง ์
๋ ฅ ํด์ฃผ์ธ์");
+ }
+ }
+
+ public static void isDifferentNumbers(int[] numbers) {
+
+ if (isSameNumber(numbers[0], numbers[1]) || isSameNumber(numbers[0], numbers[2]) || isSameNumber(numbers[1], numbers[2])) {
+ throw new IllegalArgumentException("์๋ก ๋ค๋ฅธ ์๋ฅผ ์
๋ ฅํด์ฃผ์ธ์");
+ }
+ }
+
+ private static boolean isSameNumber(int number1, int number2) {
+ return number1 == number2;
+ }
+
+ public static void validateAnswer(String answer) {
+ if (!answer.equals("1") && !answer.equals("2")) {
+ throw new IllegalArgumentException("1 ๋๋ 2๋ง ์
๋ ฅ ํด ์ฃผ์ธ์");
+ }
+ }
+ }
+} | Java | (nit) Inner class๋ก ๋์ค๊ฑฐ๋ฉด Validator์ ๋ด๋ถ ๋ฉ์๋ ๋ชจ๋ private์ผ๋ก ํ๋๊ฒ ์ข๊ฒ ์ด์. |
@@ -0,0 +1,65 @@
+
+package basball.view;
+
+import basball.baseball.model.GameStatus;
+
+import java.util.Arrays;
+import java.util.Scanner;
+import java.util.regex.Pattern;
+
+public final class InputView {
+
+ private static final String INPUT_NUMBER_MESSAGE = "์ซ์๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์ : ";
+ private static final Scanner sc = new Scanner(System.in);
+
+ public int[] getInputNumber() {
+ System.out.print(INPUT_NUMBER_MESSAGE);
+ String next = sc.next().trim();
+
+ Validator.hasThreeNumber(next);
+
+ return getNumberArray(next);
+ }
+
+ private int[] getNumberArray(String next) {
+ return Arrays.stream(next.split("")).mapToInt(value -> Integer.parseInt(value)).toArray();
+ }
+
+ public GameStatus getRestartInput() {
+ String answer = sc.next();
+ Validator.validateAnswer(answer);
+
+ if (answer.equals("1")) {
+ return GameStatus.RUNNING;
+ }
+ return GameStatus.END;
+ }
+
+ public static class Validator {
+ private static final Pattern PATTERN = Pattern.compile("[1-9]{3}");
+
+ public static void hasThreeNumber(String next) {
+
+ if (!PATTERN.matcher(next).matches()) {
+ throw new IllegalArgumentException("์๋ก ๋ค๋ฅธ 3์๋ฆฌ ์ซ์๋ง ์
๋ ฅ ํด์ฃผ์ธ์");
+ }
+ }
+
+ public static void isDifferentNumbers(int[] numbers) {
+
+ if (isSameNumber(numbers[0], numbers[1]) || isSameNumber(numbers[0], numbers[2]) || isSameNumber(numbers[1], numbers[2])) {
+ throw new IllegalArgumentException("์๋ก ๋ค๋ฅธ ์๋ฅผ ์
๋ ฅํด์ฃผ์ธ์");
+ }
+ }
+
+ private static boolean isSameNumber(int number1, int number2) {
+ return number1 == number2;
+ }
+
+ public static void validateAnswer(String answer) {
+ if (!answer.equals("1") && !answer.equals("2")) {
+ throw new IllegalArgumentException("1 ๋๋ 2๋ง ์
๋ ฅ ํด ์ฃผ์ธ์");
+ }
+ }
+ }
+} | Java | ๋ฉํ ๋ ์๋
ํ์ธ์ ! ๋ต๋ณ ๋จ๊ฒจ์ฃผ์
์ ๊ฐ์ฌํฉ๋๋ค ๊ทธ๋ฐ๋ฐ Validator ๋ฅผ private ๋ก ๋ฐ๊พธ๋ฉด Balls ๋ InputView ํ
์คํธ ๊ฐ์ ๊ณณ ์์๋ ์ด๋ป๊ฒ ์ฌ์ฉํด์ผ ํ๋์ ?
์ ์๊ฐ์ผ๋ก๋ InputView ์์ get ๋ฉ์๋๋ก ์ ๊ทผ ๋ฉ์๋๋ฅผ ์ ๊ณตํ๋ ๋ฐฉ๋ฒ ๋ฟ์ธ๋ฐ ์ด๋ ๊ฒ ๋๋ฉด InputView ํ
์คํธ๋ ๊ทธ๋ ๋ค ์ณ๋ Balls ๋ถ๋ถ์์ Validator ๋ฅผ ์ฌ์ฉํ๊ธฐ ์ํด ๋ถํ์ํ๊ฒ InputView ๊ฐ์ฒด๋ฅผ ๋ง๋ค์ด์ผ ํ๋๋ฐ ๋ง์๊น์ !?
์๋๋ฉด ์ ๋ฒ์ ๋จ๊ฒจ์ฃผ์ static class ๋ก ๋ฐ๊พธ๋ผ๋๊ฒ ์ด๋ ๊ฒ ๋ฐ๊พธ๋ผ๊ณ ํ์ ๊ฒ ์๋์๋์ !?? |
@@ -0,0 +1,65 @@
+
+package basball.view;
+
+import basball.baseball.model.GameStatus;
+
+import java.util.Arrays;
+import java.util.Scanner;
+import java.util.regex.Pattern;
+
+public final class InputView {
+
+ private static final String INPUT_NUMBER_MESSAGE = "์ซ์๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์ : ";
+ private static final Scanner sc = new Scanner(System.in);
+
+ public int[] getInputNumber() {
+ System.out.print(INPUT_NUMBER_MESSAGE);
+ String next = sc.next().trim();
+
+ Validator.hasThreeNumber(next);
+
+ return getNumberArray(next);
+ }
+
+ private int[] getNumberArray(String next) {
+ return Arrays.stream(next.split("")).mapToInt(value -> Integer.parseInt(value)).toArray();
+ }
+
+ public GameStatus getRestartInput() {
+ String answer = sc.next();
+ Validator.validateAnswer(answer);
+
+ if (answer.equals("1")) {
+ return GameStatus.RUNNING;
+ }
+ return GameStatus.END;
+ }
+
+ public static class Validator {
+ private static final Pattern PATTERN = Pattern.compile("[1-9]{3}");
+
+ public static void hasThreeNumber(String next) {
+
+ if (!PATTERN.matcher(next).matches()) {
+ throw new IllegalArgumentException("์๋ก ๋ค๋ฅธ 3์๋ฆฌ ์ซ์๋ง ์
๋ ฅ ํด์ฃผ์ธ์");
+ }
+ }
+
+ public static void isDifferentNumbers(int[] numbers) {
+
+ if (isSameNumber(numbers[0], numbers[1]) || isSameNumber(numbers[0], numbers[2]) || isSameNumber(numbers[1], numbers[2])) {
+ throw new IllegalArgumentException("์๋ก ๋ค๋ฅธ ์๋ฅผ ์
๋ ฅํด์ฃผ์ธ์");
+ }
+ }
+
+ private static boolean isSameNumber(int number1, int number2) {
+ return number1 == number2;
+ }
+
+ public static void validateAnswer(String answer) {
+ if (!answer.equals("1") && !answer.equals("2")) {
+ throw new IllegalArgumentException("1 ๋๋ 2๋ง ์
๋ ฅ ํด ์ฃผ์ธ์");
+ }
+ }
+ }
+} | Java | ์ ์ ๋จ๊ฒจ๋๋ฆฐ๊ฑด static ๊ฐ๋ณ ํด๋์ค๋ก ๋๋ผ๋ ์๊ธฐ์์ด์ ใ
ใ
์ ๊ฐ private๋ก ํ๋ผ๊ณ ๋ง์๋๋ฆฐ๊ฑด ์ฌ์ค InputView ๋ด์์๋ง ์ฐ์ฌ์ ๊ทธ๋ ๊ฒ ๋ง์๋๋ฆฐ๊ฑฐ์์ด์. ๋ง์ฝ Validator ์์ฒด๊ฐ ๋ฐ์ผ๋ก ๋์์์ ์ด์ ๊ฐ ์๋ค๋ฉด ํ
์คํธ๋ ํ์์๋๊ฑฐ๊ฒ ์ฃ . (์บก์ํ์ ์๋ฏธ์์ด์. Validator๋ฅผ ๊ฐ์ ธ๋ค ์ธ ๋ฐ๊ฐ InputView ์ธ์ ์๋ค๋ฉด ๊ตณ์ด Validator๊ฐ ์ด๋ป๊ฒ ๊ตฌํ๋์๋์ง ํ
์คํธ๋ฅผ ์ด๋ป๊ฒ ํ ์ง๋ ๊ณ ๋ฏผํ ํ์๊ฐ ์๋๊ฑฐ๊ฒ ์ฃ )
ํ์ง๋ง Validator๊ฐ ๋ค๋ฅธ๋ฐ์๋ ์ฐ์ผ๊ฑฐ๋ผ๋ฉด ๊ฐ๋ณ static ํด๋์ค๋ก ๋นผ๋๋๊ฒ ๋ ์ข์ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,65 @@
+
+package basball.view;
+
+import basball.baseball.model.GameStatus;
+
+import java.util.Arrays;
+import java.util.Scanner;
+import java.util.regex.Pattern;
+
+public final class InputView {
+
+ private static final String INPUT_NUMBER_MESSAGE = "์ซ์๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์ : ";
+ private static final Scanner sc = new Scanner(System.in);
+
+ public int[] getInputNumber() {
+ System.out.print(INPUT_NUMBER_MESSAGE);
+ String next = sc.next().trim();
+
+ Validator.hasThreeNumber(next);
+
+ return getNumberArray(next);
+ }
+
+ private int[] getNumberArray(String next) {
+ return Arrays.stream(next.split("")).mapToInt(value -> Integer.parseInt(value)).toArray();
+ }
+
+ public GameStatus getRestartInput() {
+ String answer = sc.next();
+ Validator.validateAnswer(answer);
+
+ if (answer.equals("1")) {
+ return GameStatus.RUNNING;
+ }
+ return GameStatus.END;
+ }
+
+ public static class Validator {
+ private static final Pattern PATTERN = Pattern.compile("[1-9]{3}");
+
+ public static void hasThreeNumber(String next) {
+
+ if (!PATTERN.matcher(next).matches()) {
+ throw new IllegalArgumentException("์๋ก ๋ค๋ฅธ 3์๋ฆฌ ์ซ์๋ง ์
๋ ฅ ํด์ฃผ์ธ์");
+ }
+ }
+
+ public static void isDifferentNumbers(int[] numbers) {
+
+ if (isSameNumber(numbers[0], numbers[1]) || isSameNumber(numbers[0], numbers[2]) || isSameNumber(numbers[1], numbers[2])) {
+ throw new IllegalArgumentException("์๋ก ๋ค๋ฅธ ์๋ฅผ ์
๋ ฅํด์ฃผ์ธ์");
+ }
+ }
+
+ private static boolean isSameNumber(int number1, int number2) {
+ return number1 == number2;
+ }
+
+ public static void validateAnswer(String answer) {
+ if (!answer.equals("1") && !answer.equals("2")) {
+ throw new IllegalArgumentException("1 ๋๋ 2๋ง ์
๋ ฅ ํด ์ฃผ์ธ์");
+ }
+ }
+ }
+} | Java | ์๋
ํ์ธ์ ๋ฉํ ๋ ! `๊ฐ๋ณ static ํด๋์ค` ๋ผ๋ ๋ง์ด ์ ์ดํด๊ฐ ์๋๋๋ฐ ํน์ `Math` ํด๋์ค ์ฒ๋ผ `final ๊ณผ private ์์ฑ์` ๋ฅผ ํตํด ์์ฑ์ ๋ง๊ณ ๋จ์ง `Utils` ํด๋์ค ์ฒ๋ผ ์ฌ์ฉ ์ ์๋ฏธ ํ์๋๊ฑด๊ฐ์ ? ?์๋๋ฉด
์ธ๋ถ๋ `public ํด๋์ค` ๋ก ๋ง๋ค๊ณ ๋ด๋ถ์ `public static class` ๋ก ๋ง๋ค๋ผ๊ณ ํ์๋ ๊ฑด๊ฐ์ ??
< final ์ฌ์ฉ >
```
public final class Validator {
private Validator() {
}
private static final Pattern PATTERN = Pattern.compile("[1-9]{3}");
public static void hasThreeNumber(String next) {
if (!PATTERN.matcher(next).matches()) {
throw new IllegalArgumentException("์๋ก ๋ค๋ฅธ 3์๋ฆฌ ์ซ์๋ง ์
๋ ฅ ํด์ฃผ์ธ์");
}
}
...
}
```
< static ์ฌ์ฉ >
```
public class Validators {
public static class Validator {
private static final Pattern PATTERN = Pattern.compile("[1-9]{3}");
public static void hasThreeNumber(String next) {
if (!PATTERN.matcher(next).matches()) {
throw new IllegalArgumentException("์๋ก ๋ค๋ฅธ 3์๋ฆฌ ์ซ์๋ง ์
๋ ฅ ํด์ฃผ์ธ์");
}
}
...
}
}
``` |
@@ -0,0 +1,65 @@
+
+package basball.view;
+
+import basball.baseball.model.GameStatus;
+
+import java.util.Arrays;
+import java.util.Scanner;
+import java.util.regex.Pattern;
+
+public final class InputView {
+
+ private static final String INPUT_NUMBER_MESSAGE = "์ซ์๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์ : ";
+ private static final Scanner sc = new Scanner(System.in);
+
+ public int[] getInputNumber() {
+ System.out.print(INPUT_NUMBER_MESSAGE);
+ String next = sc.next().trim();
+
+ Validator.hasThreeNumber(next);
+
+ return getNumberArray(next);
+ }
+
+ private int[] getNumberArray(String next) {
+ return Arrays.stream(next.split("")).mapToInt(value -> Integer.parseInt(value)).toArray();
+ }
+
+ public GameStatus getRestartInput() {
+ String answer = sc.next();
+ Validator.validateAnswer(answer);
+
+ if (answer.equals("1")) {
+ return GameStatus.RUNNING;
+ }
+ return GameStatus.END;
+ }
+
+ public static class Validator {
+ private static final Pattern PATTERN = Pattern.compile("[1-9]{3}");
+
+ public static void hasThreeNumber(String next) {
+
+ if (!PATTERN.matcher(next).matches()) {
+ throw new IllegalArgumentException("์๋ก ๋ค๋ฅธ 3์๋ฆฌ ์ซ์๋ง ์
๋ ฅ ํด์ฃผ์ธ์");
+ }
+ }
+
+ public static void isDifferentNumbers(int[] numbers) {
+
+ if (isSameNumber(numbers[0], numbers[1]) || isSameNumber(numbers[0], numbers[2]) || isSameNumber(numbers[1], numbers[2])) {
+ throw new IllegalArgumentException("์๋ก ๋ค๋ฅธ ์๋ฅผ ์
๋ ฅํด์ฃผ์ธ์");
+ }
+ }
+
+ private static boolean isSameNumber(int number1, int number2) {
+ return number1 == number2;
+ }
+
+ public static void validateAnswer(String answer) {
+ if (!answer.equals("1") && !answer.equals("2")) {
+ throw new IllegalArgumentException("1 ๋๋ 2๋ง ์
๋ ฅ ํด ์ฃผ์ธ์");
+ }
+ }
+ }
+} | Java | ์ ์..์ ๊ฐ ๋ง์๋๋ฆฐ๊ฑธ ๋๋ฌด ํฌ๊ฒ ์๊ฐํ์ ๊ฒ ๊ฐ๊ตฐ์..^^;
์ ๊ฐ ๋ง์๋๋ฆฐ๊ฑด ๋จ์ํ Validator.java ํ์ผ์ ํ๋ ๋ ๋ง๋ค์ด์ ๊ฑฐ๊ธฐ๋ค ๋ฃ๋๋ค๋ ์๊ธฐ์์ด์.
๊ทธ๋ฌ๋ฉด ๊ตณ์ด InputView์ ์ข
์์ ์ธ namespace๋ฅผ ๊ฐ์ง ํ์๊ฐ ์์ผ๋๊น์ ใ
ใ
|
@@ -88,5 +88,186 @@ export default {
display: flex;
align-items: center;
justify-content: center;
+ html,
+ body {
+ height: 100%;
+ width: 100%;
+ padding: 0;
+ margin: 0;
+ }
+ .container {
+ background: white;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ flex-wrap: nowrap;
+ }
+ .container .main {
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ }
+
+ .container .main-content {
+ background-color: #7278c6;
+ display: flex;
+ flex: 1;
+ height: 100%;
+ color: #f0f0f6;
+ flex-direction: column;
+ align-items: center;
+ padding-top: 20px;
+ font-weight: bold;
+ font-size: 20px;
+ }
+ .container .main-center {
+ display: flex;
+ background-color: #f7f7f7;
+ flex: 1;
+ height: 100%;
+ justify-content: center;
+
+ position: relative;
+ }
+ .main-center .car-card {
+ display: flex;
+ flex-direction: column;
+ width: 70%;
+ background-color: #ffffff;
+ justify-content: center;
+ padding: 10px 30px;
+ position: absolute;
+ top: -100px;
+ }
+ .main-center .car-card .top {
+ display: flex;
+ justify-content: center;
+ }
+ .main-center .car-card .bottom {
+ display: flex;
+ }
+
+ .main-center .car-card .bottom .left {
+ display: flex;
+ flex-direction: column;
+ flex: 1;
+ font-weight: bold;
+ }
+
+ .main-center .car-card .bottom .right {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-end;
+ flex: 1;
+ }
+
+ .container .main-center-footer {
+ display: flex;
+ color: #5c63b9;
+ align-items: flex-end;
+ justify-content: start;
+ background-color: #f7f7f7;
+ font-weight: bold;
+ padding: 10px 30px;
+ }
+
+ .container .main-bottom {
+ display: flex;
+ flex: 1;
+ height: 100%;
+ flex-direction: column;
+ }
+
+ .main-bottom .content {
+ display: flex;
+ height: 100%;
+ }
+ .main-bottom .content .left {
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ justify-content: flex-start;
+ }
+
+ .main-bottom .content .right-img {
+ display: flex;
+ flex: 1;
+ align-items: flex-start;
+ justify-content: center;
+ }
+ .main-bottom .content .right-img img {
+ width: 200px;
+ height: 120px;
+ }
+
+ .main-bottom .first-line {
+ display: flex;
+ padding-left: 30px;
+ margin: 10px 0px;
+ }
+
+ .main-bottom .first-line .left-txt {
+ display: flex;
+ justify-content: center;
+ background-color: #565db7;
+ flex: 1;
+ font-size: 12px;
+ color: #f6f7fb;
+ padding: 3px;
+ }
+
+ .main-bottom .first-line .right {
+ display: flex;
+ padding-left: 10px;
+ flex: 3;
+ font-weight: bold;
+ }
+
+ .main-bottom .second-line {
+ display: flex;
+ padding-left: 30px;
+ font-size: 15px;
+ color: #5e5e5e;
+ }
+
+ .main-bottom .third-line {
+ display: flex;
+ padding-left: 30px;
+ font-size: 15px;
+ color: #c6c6d1;
+ }
+ .main-bottom .fourth-line {
+ display: flex;
+ padding-left: 30px;
+ color: #555555;
+ font-weight: bold;
+ }
+
+ .main-bottom .last-line {
+ display: flex;
+ padding: 10px;
+ border-top: solid 1px #f7f7f7;
+ }
+ .main-bottom .last-line .left {
+ display: flex;
+ justify-content: center;
+ flex: 1;
+ color: #575cb5;
+ font-weight: bold;
+ }
+ .main-bottom .last-line .right {
+ display: flex;
+ justify-content: center;
+ flex: 1;
+ color: #575cb5;
+ font-weight: bold;
+ }
+
+ .container .event {
+ display: flex;
+ flex: 1;
+ background-color: #f7f7f7;
+ }
}
</style>
\ No newline at end of file | Unknown | ์ฌ๊ธฐ์ด๋ ๊ฒํ๋ฉด์๋ผ์ |
@@ -88,5 +88,186 @@ export default {
display: flex;
align-items: center;
justify-content: center;
+ html,
+ body {
+ height: 100%;
+ width: 100%;
+ padding: 0;
+ margin: 0;
+ }
+ .container {
+ background: white;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ flex-wrap: nowrap;
+ }
+ .container .main {
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ }
+
+ .container .main-content {
+ background-color: #7278c6;
+ display: flex;
+ flex: 1;
+ height: 100%;
+ color: #f0f0f6;
+ flex-direction: column;
+ align-items: center;
+ padding-top: 20px;
+ font-weight: bold;
+ font-size: 20px;
+ }
+ .container .main-center {
+ display: flex;
+ background-color: #f7f7f7;
+ flex: 1;
+ height: 100%;
+ justify-content: center;
+
+ position: relative;
+ }
+ .main-center .car-card {
+ display: flex;
+ flex-direction: column;
+ width: 70%;
+ background-color: #ffffff;
+ justify-content: center;
+ padding: 10px 30px;
+ position: absolute;
+ top: -100px;
+ }
+ .main-center .car-card .top {
+ display: flex;
+ justify-content: center;
+ }
+ .main-center .car-card .bottom {
+ display: flex;
+ }
+
+ .main-center .car-card .bottom .left {
+ display: flex;
+ flex-direction: column;
+ flex: 1;
+ font-weight: bold;
+ }
+
+ .main-center .car-card .bottom .right {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-end;
+ flex: 1;
+ }
+
+ .container .main-center-footer {
+ display: flex;
+ color: #5c63b9;
+ align-items: flex-end;
+ justify-content: start;
+ background-color: #f7f7f7;
+ font-weight: bold;
+ padding: 10px 30px;
+ }
+
+ .container .main-bottom {
+ display: flex;
+ flex: 1;
+ height: 100%;
+ flex-direction: column;
+ }
+
+ .main-bottom .content {
+ display: flex;
+ height: 100%;
+ }
+ .main-bottom .content .left {
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ justify-content: flex-start;
+ }
+
+ .main-bottom .content .right-img {
+ display: flex;
+ flex: 1;
+ align-items: flex-start;
+ justify-content: center;
+ }
+ .main-bottom .content .right-img img {
+ width: 200px;
+ height: 120px;
+ }
+
+ .main-bottom .first-line {
+ display: flex;
+ padding-left: 30px;
+ margin: 10px 0px;
+ }
+
+ .main-bottom .first-line .left-txt {
+ display: flex;
+ justify-content: center;
+ background-color: #565db7;
+ flex: 1;
+ font-size: 12px;
+ color: #f6f7fb;
+ padding: 3px;
+ }
+
+ .main-bottom .first-line .right {
+ display: flex;
+ padding-left: 10px;
+ flex: 3;
+ font-weight: bold;
+ }
+
+ .main-bottom .second-line {
+ display: flex;
+ padding-left: 30px;
+ font-size: 15px;
+ color: #5e5e5e;
+ }
+
+ .main-bottom .third-line {
+ display: flex;
+ padding-left: 30px;
+ font-size: 15px;
+ color: #c6c6d1;
+ }
+ .main-bottom .fourth-line {
+ display: flex;
+ padding-left: 30px;
+ color: #555555;
+ font-weight: bold;
+ }
+
+ .main-bottom .last-line {
+ display: flex;
+ padding: 10px;
+ border-top: solid 1px #f7f7f7;
+ }
+ .main-bottom .last-line .left {
+ display: flex;
+ justify-content: center;
+ flex: 1;
+ color: #575cb5;
+ font-weight: bold;
+ }
+ .main-bottom .last-line .right {
+ display: flex;
+ justify-content: center;
+ flex: 1;
+ color: #575cb5;
+ font-weight: bold;
+ }
+
+ .container .event {
+ display: flex;
+ flex: 1;
+ background-color: #f7f7f7;
+ }
}
</style>
\ No newline at end of file | Unknown | ์์ ํ์ต๋๋ค |
@@ -0,0 +1,105 @@
+import { Helmet } from 'react-helmet-async';
+import titles from '../routes/titles';
+import styled from 'styled-components';
+import MainCard from './components/MainCard';
+import Tag from './components/Tag';
+import Card from './components/Card';
+import { useQuery } from 'react-query';
+import { getArticles } from '../api/ArticlesController';
+import { useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+
+const BlogWrapper = styled.div`
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ width: 100%;
+ margin: 0px 120px 0px 120px;
+`;
+
+const TagBox = styled.div`
+ display: flex;
+ gap: 10px;
+ margin-bottom: 44px;
+ margin: 0px 48px;
+`;
+
+const CardBox = styled.div`
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ row-gap: 3rem;
+ column-gap: 6rem;
+ margin: 44px 48px 0px 48px;
+
+ a {
+ display: flex;
+ justify-items: center;
+ justify-content: center;
+ }
+`;
+
+function BlogPage() {
+ const navigate = useNavigate();
+
+ const {
+ data: cardData,
+ isLoading,
+ error,
+ } = useQuery({
+ queryKey: ['articles'],
+ queryFn: getArticles,
+ });
+
+ const [activeTag, setActiveTag] = useState('์ ์ฒด');
+
+ if (isLoading) return 'Loading...';
+
+ if (error) return 'An error has occurred: ' + error;
+
+ if (!cardData || cardData.length === 0) return 'No data available';
+
+ const mainCardData = cardData[0];
+
+ const categories = [
+ { id: 0, text: '์ ์ฒด' },
+ { id: 1, text: '๋ฌธํ' },
+ { id: 2, text: '์๋น์ค' },
+ { id: 3, text: '์ปค๋ฆฌ์ด' },
+ ];
+
+ return (
+ <>
+ <Helmet>
+ <title>{titles.blog}</title>
+ </Helmet>
+ <BlogWrapper>
+ <MainCard
+ mainCard={mainCardData}
+ onClick={()=>navigate(`/blog/${mainCardData.articleId}`)}
+ />
+ <TagBox>
+ {categories.map((category) => (
+ <Tag
+ key={category.id}
+ text={category.text}
+ onClick={() => setActiveTag(category.text)}
+ isActive={category.text === activeTag}
+ />
+ ))}
+ </TagBox>
+ <CardBox>
+ {cardData.map((card) => (
+ <Card
+ key={card.articleId}
+ card={card}
+ isActive={card.categories[0] === activeTag || '์ ์ฒด' === activeTag }
+ onClick={()=>navigate(`/blog/${card.articleId}`)}
+ />
+ ))}
+ </CardBox>
+ </BlogWrapper>
+ </>
+ );
+}
+
+export default BlogPage; | Unknown | P4: margin์ด๋ margin-bottom ๊ฐ์ด ์ด ์ด์ ๊ฐ ์์๊น์? ํ๋๋ก ํต์ผํ๋ฉด ๋ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,105 @@
+import { Helmet } from 'react-helmet-async';
+import titles from '../routes/titles';
+import styled from 'styled-components';
+import MainCard from './components/MainCard';
+import Tag from './components/Tag';
+import Card from './components/Card';
+import { useQuery } from 'react-query';
+import { getArticles } from '../api/ArticlesController';
+import { useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+
+const BlogWrapper = styled.div`
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ width: 100%;
+ margin: 0px 120px 0px 120px;
+`;
+
+const TagBox = styled.div`
+ display: flex;
+ gap: 10px;
+ margin-bottom: 44px;
+ margin: 0px 48px;
+`;
+
+const CardBox = styled.div`
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ row-gap: 3rem;
+ column-gap: 6rem;
+ margin: 44px 48px 0px 48px;
+
+ a {
+ display: flex;
+ justify-items: center;
+ justify-content: center;
+ }
+`;
+
+function BlogPage() {
+ const navigate = useNavigate();
+
+ const {
+ data: cardData,
+ isLoading,
+ error,
+ } = useQuery({
+ queryKey: ['articles'],
+ queryFn: getArticles,
+ });
+
+ const [activeTag, setActiveTag] = useState('์ ์ฒด');
+
+ if (isLoading) return 'Loading...';
+
+ if (error) return 'An error has occurred: ' + error;
+
+ if (!cardData || cardData.length === 0) return 'No data available';
+
+ const mainCardData = cardData[0];
+
+ const categories = [
+ { id: 0, text: '์ ์ฒด' },
+ { id: 1, text: '๋ฌธํ' },
+ { id: 2, text: '์๋น์ค' },
+ { id: 3, text: '์ปค๋ฆฌ์ด' },
+ ];
+
+ return (
+ <>
+ <Helmet>
+ <title>{titles.blog}</title>
+ </Helmet>
+ <BlogWrapper>
+ <MainCard
+ mainCard={mainCardData}
+ onClick={()=>navigate(`/blog/${mainCardData.articleId}`)}
+ />
+ <TagBox>
+ {categories.map((category) => (
+ <Tag
+ key={category.id}
+ text={category.text}
+ onClick={() => setActiveTag(category.text)}
+ isActive={category.text === activeTag}
+ />
+ ))}
+ </TagBox>
+ <CardBox>
+ {cardData.map((card) => (
+ <Card
+ key={card.articleId}
+ card={card}
+ isActive={card.categories[0] === activeTag || '์ ์ฒด' === activeTag }
+ onClick={()=>navigate(`/blog/${card.articleId}`)}
+ />
+ ))}
+ </CardBox>
+ </BlogWrapper>
+ </>
+ );
+}
+
+export default BlogPage; | Unknown | P1: suspense๋ก ์ฎ๊ธฐ๋ ๊ฒ ๊ณต๋ถ
https://blog.jbee.io/react/React%EC%97%90%EC%84%9C+%EC%84%A0%EC%96%B8%EC%A0%81%EC%9C%BC%EB%A1%9C+%EB%B9%84%EB%8F%99%EA%B8%B0+%EB%8B%A4%EB%A3%A8%EA%B8%B0 |
@@ -0,0 +1,32 @@
+import styled from 'styled-components';
+
+const TagWrapper = styled.div<{ $isActive: boolean }>`
+ border-radius: 40px;
+ border: none;
+ padding: 14px 20px;
+ font-size: 18px;
+ cursor: pointer;
+ line-height: 22px;
+ color: ${(props) => (props.$isActive ? '#ffffff' : '#868b94')};
+ background-color: ${(props) => (props.$isActive ? '#212124' : '#f2f3f6')};
+ font-weight: ${(props) => (props.$isActive ? '600' : '400')};
+ &:hover {
+ background-color: #212124;
+ color: #ffffff;
+ font-weight: 600;
+ }
+`;
+
+interface TagProps {
+ text: string;
+ isActive: boolean;
+ onClick: () => void;
+};
+
+export default function Tag({ isActive, onClick, text }: TagProps) {
+ return (
+ <TagWrapper $isActive={isActive} onClick={onClick}>
+ {text}
+ </TagWrapper>
+ );
+} | Unknown | P3: ์ดํ์ css variables๋ก ๋นผ์ ๊ด๋ฆฌํ๋ฉด ์ข์ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,31 @@
+class VisitDateError {
+ #notInputDate(visitDate) {
+ if (visitDate.length === 0) {
+ throw new Error('[ERROR] ๋ฐฉ๋ฌธ ๋ ์ง๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #dateNotNum(visitDate) {
+ if (
+ Number.isNaN(Number(visitDate)) ||
+ Number.isInteger(Number(visitDate)) === false ||
+ visitDate.includes('.')
+ ) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #dateNotInRange(visitDate) {
+ if (Number(visitDate) < 1 || Number(visitDate) > 31) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ valid(visitDate) {
+ this.#notInputDate(visitDate);
+ this.#dateNotNum(visitDate);
+ this.#dateNotInRange(visitDate);
+ }
+}
+
+export default VisitDateError; | JavaScript | ํด๋น ๋ถ๋ถ ์ ๊ท ํํ์์ผ๋ก ํ๋ฉด if๋ฌธ์ ํ๋๋ก ์ค์ผ ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค ! |
@@ -0,0 +1,31 @@
+class VisitDateError {
+ #notInputDate(visitDate) {
+ if (visitDate.length === 0) {
+ throw new Error('[ERROR] ๋ฐฉ๋ฌธ ๋ ์ง๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #dateNotNum(visitDate) {
+ if (
+ Number.isNaN(Number(visitDate)) ||
+ Number.isInteger(Number(visitDate)) === false ||
+ visitDate.includes('.')
+ ) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #dateNotInRange(visitDate) {
+ if (Number(visitDate) < 1 || Number(visitDate) > 31) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ valid(visitDate) {
+ this.#notInputDate(visitDate);
+ this.#dateNotNum(visitDate);
+ this.#dateNotInRange(visitDate);
+ }
+}
+
+export default VisitDateError; | JavaScript | ํด๋น ๋ฌธ๊ตฌ๋ constant์ ๋ฐ๋ก error.js๋ฅผ ์์ฑํ์
์ ํ์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค ! |
@@ -0,0 +1,61 @@
+import { MENU_NAMES, MENUS } from '../../constant/menu.js';
+
+class OrderMenuError {
+ #orderNotInput(orderMenu) {
+ if (
+ orderMenu.length === 1 &&
+ orderMenu[0].menu.trim() === ''
+ ) {
+ throw new Error('[ERROR] ์ฃผ๋ฌธํ์ค ๋ฉ๋ด์ ๊ฐ์๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #orderWrongInput(orderMenu) {
+ if (!orderMenu
+ .every((order) => Number.isNaN(order.cnt) === false &&
+ Number.isInteger(order.cnt) &&
+ order.cnt > 0)
+ ) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #orderNotExistMenu(orderMenu) {
+ if (!orderMenu.every((order) => MENU_NAMES.includes(order.menu))) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #orderDuplication(orderMenu) {
+ const originOrderMenu = orderMenu.map((order) => order.menu);
+ const setOrderMenu = new Set(originOrderMenu);
+ if (originOrderMenu.length !== setOrderMenu.size) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #orderTypeOnlyDrink(orderMenu) {
+ const DRINK = Object.keys(MENUS.Drink);
+ if (orderMenu.every((order) => DRINK.includes(order.menu))) {
+ throw new Error('[ERROR] ์๋ฃ๋ง ์ฃผ๋ฌธํ์ค ์ ์์ต๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #totalOrderCntOverRange(orderMenu) {
+ const totalMenuCnt = orderMenu.reduce((acc, order) => acc + order.cnt, 0);
+ if (totalMenuCnt > 20) {
+ throw new Error('[ERROR] ๋ฉ๋ด๋ ์ต๋ 20๊ฐ ๊น์ง ์ฃผ๋ฌธ ๊ฐ๋ฅํฉ๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ valid(orderMenu) {
+ this.#orderNotInput(orderMenu);
+ this.#orderWrongInput(orderMenu);
+ this.#orderNotExistMenu(orderMenu);
+ this.#orderTypeOnlyDrink(orderMenu);
+ this.#orderDuplication(orderMenu);
+ this.#totalOrderCntOverRange(orderMenu);
+ }
+}
+
+export default OrderMenuError; | JavaScript | ์ ๋ ์ค์๋ก ๋์น ๋ถ๋ถ์ด์ง๋ง 1.0์ ํฌํจํ ์ง ์ํ ์ง ๊ณ ๋ฏผํ์
จ๋ค๊ณ ํ์
จ๋๋ฐ ๊ทธ ๋ถ๋ถ ์ดํดํฉ๋๋ค...
๋ฏธ์
์ด ๋๋๊ณ ์๊ฐ๋๊ฑฐ์ง๋ง 1.0๋ ํฌํจ์ ํ๋ค๋ฉด 1.000000000000000... ๋ 1๋ก ๋๋๊ฑฐ๋ผ 0์ ๋ฌดํ๋๋ก ์
๋ ฅํ๋ฉด ๋ฌธ์ ๊ฐ ๋ฐ์ํ์ง ์์๊น ํ๋ ์ฐ๋ ค๊ฐ ๋๋๋ฐ ์ด๋ป๊ฒ ์๊ฐํ์๋์? |
@@ -0,0 +1,28 @@
+const EVENT_NAMES = ['ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ', 'ํ์ผ ํ ์ธ', '์ฃผ๋ง ํ ์ธ', 'ํน๋ณ ํ ์ธ', '์ฆ์ ์ด๋ฒคํธ'];
+
+const WEEKDAY_DISCOUNT_DATE = [
+ 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 17,
+ 18, 19, 20, 21, 24, 25, 26, 27, 28, 31,
+];
+
+const WEEKEND_DISCOUNT_DATE = [
+ 1, 2, 8, 9, 15, 16, 22, 23, 29, 30,
+];
+
+const SPECIAL_DISCOUNT_DATE = [
+ 3, 10, 17, 24, 25, 31,
+];
+
+Object.freeze(
+ EVENT_NAMES,
+ WEEKDAY_DISCOUNT_DATE,
+ WEEKEND_DISCOUNT_DATE,
+ SPECIAL_DISCOUNT_DATE,
+);
+
+export {
+ EVENT_NAMES,
+ WEEKDAY_DISCOUNT_DATE,
+ WEEKEND_DISCOUNT_DATE,
+ SPECIAL_DISCOUNT_DATE,
+}; | JavaScript | ํด๋น ๋ถ๋ถ์ `new Date()` ๋ฉ์๋๋ก ํํ์ด ๊ฐ๋ฅํ ๊ฒ ๊ฐ์ต๋๋ค !
`new Date()`๋ฅผ ์ฌ์ฉํ์๋ฉด 0-์ผ์์ผ ~ 6-ํ ์์ผ๋ก 0~6๊น์ง์ number๋ก ์ถ๋ ฅ๋ฉ๋๋ค ! |
@@ -0,0 +1,66 @@
+import OUTPUT from '../../utils/constant/output.js';
+import OutputView from '../../utils/view_type/OutputView.js';
+import { EVENT_NAMES } from '../../utils/constant/event.js';
+
+class PrintEventResult {
+ #totalOrderAmount(TOTAL_AMOUNT) {
+ OutputView.printOutput(`${OUTPUT.TOTAL_AMOUNT.BEFORE_DISCOUNT}`);
+ OutputView.printOutput(`${TOTAL_AMOUNT.toLocaleString()}์`);
+ OutputView.printOutput('');
+ }
+
+ #giveawayMenu(GIVEAWAY_MENU) {
+ OutputView.printOutput(`${OUTPUT.MENU.GIVEAWAY_MENU}`);
+ OutputView.printOutput(`${GIVEAWAY_MENU}`);
+ OutputView.printOutput('');
+ }
+
+ #eventDetails(EVENT_DETAILS_RESULT) {
+ if (EVENT_DETAILS_RESULT === '์์') {
+ OutputView.printOutput(`${OUTPUT.BENEFIT.LIST}`);
+ OutputView.printOutput(`${EVENT_DETAILS_RESULT}`);
+ OutputView.printOutput('');
+ return;
+ }
+ this.#validEventDetails(EVENT_DETAILS_RESULT);
+ }
+
+ #validEventDetails(EVENT_DETAILS_RESULT) {
+ OutputView.printOutput(OUTPUT.BENEFIT.LIST);
+ Object.keys(EVENT_DETAILS_RESULT).forEach((event, idx) => {
+ if (EVENT_DETAILS_RESULT[event] > 0) {
+ OutputView.printOutput(`${EVENT_NAMES[idx]}: -${EVENT_DETAILS_RESULT[event].toLocaleString()}์`);
+ }
+ });
+ OutputView.printOutput('');
+ }
+
+ #totalBenefitAmount(BENEFIT_AMOUNT_RESULT) {
+ OutputView.printOutput(`${OUTPUT.BENEFIT.TOTAL_BENEFIT_AMOUNT}`);
+ OutputView.printOutput(`-${BENEFIT_AMOUNT_RESULT.toLocaleString()}์`);
+ OutputView.printOutput('');
+ }
+
+ #expectPaymentAmount(EXPEXT_PAYMENT_AMOUNT) {
+ OutputView.printOutput(`${OUTPUT.TOTAL_AMOUNT.AFTER_DISCOUNT}`);
+ OutputView.printOutput(`${EXPEXT_PAYMENT_AMOUNT.toLocaleString()}์`);
+ OutputView.printOutput('');
+ }
+
+ #evnetBadge(BADGE) {
+ OutputView.printOutput(`${OUTPUT.EVENT.BADGE}`);
+ OutputView.printOutput(`${BADGE}`);
+ OutputView.printOutput('');
+ }
+
+ print(AMOUNT_RESULT, BENEFIT_RESULT) {
+ this.#totalOrderAmount(AMOUNT_RESULT.TOTAL_AMOUNT);
+ this.#giveawayMenu(BENEFIT_RESULT.GIVEAWAY_MENU);
+ this.#eventDetails(BENEFIT_RESULT.EVENT_DETAILS_RESULT);
+ this.#totalBenefitAmount(AMOUNT_RESULT.BENEFIT_AMOUNT_RESULT);
+ this.#expectPaymentAmount(AMOUNT_RESULT.EXPECT_PAYMENT_AMOUNT);
+ this.#evnetBadge(BENEFIT_RESULT.BADGE);
+ }
+}
+
+export default PrintEventResult; | JavaScript | ```jsx
OutputView.printOutput('');
```
์ด ๋ฌธ๊ตฌ ๊ฐํ๋๋ฌธ์ ์
๋ ฅํ์ ๊ฒ ๊ฐ์๋ฐ `์`๋ ๋ณ์ํ ํ์
์ `์\n`์ ํ์
๋ ๋๊ณ
๊ทธ ๋ค์ ๋ฌธ๊ตฌ์ `OutputView.printOutput(${OUTPUT.EVENT.BADGE});`๊ฐ ๋์ค๋
`BADGE: '\n<12์ ์ด๋ฒคํธ ๋ฐฐ์ง>'` ์ด๋ฐ์์ผ๋ก ์ถ๊ฐํ๋ฉด ์ฝ๋๊ฐ ์กฐ๊ธ ๋ ๊น๋ํด ์ง ๊ฒ ๊ฐ์์ ! |
@@ -0,0 +1,56 @@
+import { WEEKDAY_DISCOUNT_DATE, WEEKEND_DISCOUNT_DATE, SPECIAL_DISCOUNT_DATE } from '../../utils/constant/event.js';
+import { MENUS } from '../../utils/constant/menu.js';
+
+class CalculateEventBenefit {
+ #event = {
+ christmas: 0,
+ weekday: 0,
+ weekend: 0,
+ special: 0,
+ giveaway: 0,
+ };
+
+ #christmasEvent(visitDate) {
+ if (visitDate > 0 && visitDate < 26) {
+ this.#event.christmas = 1000 + (visitDate - 1) * 100;
+ }
+ }
+
+ #specialEvent(visitDate) {
+ if (SPECIAL_DISCOUNT_DATE.includes(visitDate)) {
+ this.#event.special = 1000;
+ }
+ }
+
+ #weekdayEvent(order, DESSERT, visitDate) {
+ if (
+ WEEKDAY_DISCOUNT_DATE.includes(visitDate) &&
+ DESSERT.includes(order.menu)
+ ) {
+ this.#event.weekday += 2023 * order.cnt;
+ }
+ }
+
+ #weekendEvent(order, MAIN, visitDate) {
+ if (
+ WEEKEND_DISCOUNT_DATE.includes(visitDate) &&
+ MAIN.includes(order.menu)
+ ) {
+ this.#event.weekend += 2023 * order.cnt;
+ }
+ }
+
+ result(visitDate, orderMenu) {
+ const DESSERT = Object.keys(MENUS.Dessert);
+ const MAIN = Object.keys(MENUS.Main);
+ this.#christmasEvent(visitDate);
+ this.#specialEvent(visitDate);
+ orderMenu.forEach((order) => {
+ this.#weekdayEvent(order, DESSERT, visitDate);
+ this.#weekendEvent(order, MAIN, visitDate);
+ });
+ return this.#event;
+ }
+}
+
+export default CalculateEventBenefit; | JavaScript | ```jsx
#event = {
christmas: 0,
weekday: 0,
weekend: 0,
special: 0,
giveaway: 0,
};
```
์ด๋ ๊ฒ ์์ฑํ์ ๊ฒ ์ฒ๋ผ ํด๋น ์์ ๊ฐ๋ ๊ณ ์ ๊ฐ์ด๋ ๋ณ์ํํด์ ์๋ฏธ๋ฅผ ๋ถ์ฌํ๋ ๊ฒ๋ ๊ด์ฐฎ์ ๊ฒ ๊ฐ์ต๋๋ค ! |
@@ -0,0 +1,41 @@
+import VisitDateError from '../../../utils/error/type/visit_date_error.js';
+import printError from '../../../utils/error/print_error.js';
+import INPUT_QUESTION from '../../../utils/constant/input_question.js';
+import OUTPUT from '../../../utils/constant/output.js';
+import InputView from '../../../utils/view_type/InputView.js';
+import OutputView from '../../../utils/view_type/OutputView.js';
+
+class VisitDateManage {
+ #visitDate = null;
+
+ get getVisitDate() {
+ return this.#visitDate;
+ }
+
+ async firstGreeting() {
+ OutputView.printOutput(OUTPUT.FIRST_GREETING);
+ await this.#inputVisitDate();
+ }
+
+ async #inputVisitDate() {
+ while (true) {
+ this.#visitDate = await InputView.userInput(INPUT_QUESTION.VISIT_DATE);
+ if (this.#isValidDate()) {
+ break;
+ }
+ }
+ }
+
+ #isValidDate() {
+ const ERROR = new VisitDateError();
+ try {
+ ERROR.valid(this.#visitDate);
+ return true;
+ } catch (error) {
+ printError(error);
+ return false;
+ }
+ }
+}
+
+export default VisitDateManage; | JavaScript | ์๊ตฌ์ฌํญ์ ์๋ ๋ง์ฝ ํ์์ ๋ง์ง ์์ผ๋ฉด ์๋ก์ด ๊ฐ์ ๋ฐ์์ค๋ ๊ณผ์ ์ด ์๋๊ฒ ๊ฐ์ต๋๋ค.
(ํน์ ์ ๊ฐ ๋ชป ์ฐพ๋ ๊ฒ์ด๋ผ๋ฉด ์ ์ํด์ฃผ์๊ธฐ ๋ฐ๋๋๋ค)
ํด๋น ๊ตฌ๋ฌธ์์๋ return false๋ฅผ ํ๊ณ ๊ทธ๋ฅ break์จ์ ๋น ์ ธ ๋์จ๊ฒ ๊ฐ์๋ฐ return false ๋์ return this.#inputVisitDate() ํ๋ฉด ๋ค์ ๊ฐ์ ๋ฐ์ ์ฌ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,48 @@
+import CalculateOrderMenu from '../../model/calculate_order_menu.js';
+import PrintOrderMenu from '../../view/print_order_menu.js';
+import OrderMenuError from '../../../utils/error/type/order_menu_error.js';
+import printError from '../../../utils/error/print_error.js';
+import INPUT_QUESTION from '../../../utils/constant/input_question.js';
+import InputView from '../../../utils/view_type/InputView.js';
+
+class OrderMenuManage {
+ #orderMenu = null;
+
+ get getOrderMenu() {
+ return this.#orderMenu;
+ }
+
+ async inputOrderMenu(visitDate) {
+ while (true) {
+ this.#orderMenu = await InputView.userInput(INPUT_QUESTION.ORDER_MENU);
+ this.#orderMenu = this.#calculateOrderMenu();
+ if (this.#isValidOrderMenu()) {
+ break;
+ }
+ }
+ this.#print(visitDate);
+ }
+
+ #calculateOrderMenu() {
+ const calculateOrderMenu = new CalculateOrderMenu();
+ return calculateOrderMenu.calculate(this.#orderMenu);
+ }
+
+ #isValidOrderMenu() {
+ const ERROR = new OrderMenuError();
+ try {
+ ERROR.valid(this.#orderMenu);
+ return true;
+ } catch (error) {
+ printError(error);
+ return false;
+ }
+ }
+
+ #print(visitDate) {
+ const printOrderMenu = new PrintOrderMenu();
+ printOrderMenu.print(visitDate, this.#orderMenu);
+ }
+}
+
+export default OrderMenuManage; | JavaScript | ์ด ๋ถ๋ถ๋ ๋ ์ง ๋ฐ์์ฌ๋์ ๋ง์ฐฌ๊ฐ์ง๋ก ์๋ชป๋ ๊ฒฝ์ฐ ์ ๊ฐ์ ๊ฐ์ ธ์ค๋ ๊ณผ์ ์ด ์์ด๋ณด์
๋๋ค |
@@ -0,0 +1,67 @@
+import CalculateTotalOrderAmount from '../../model/calculate_total_order_amount.js';
+import CalculateEventDetails from '../../model/calculate_event_details.js';
+import PrintEventResult from '../../view/print_event_result.js';
+
+class EventManage {
+ #visitDate;
+ #orderMenu;
+
+ constructor(visitDate, orderMenu) {
+ this.#visitDate = Number(visitDate);
+ this.#orderMenu = orderMenu;
+ }
+
+ totalOrderAmount() {
+ const TOTAL_AMOUNT = this.#calculateTotalOrderAmount();
+ if (TOTAL_AMOUNT < 10000) {
+ return this.#printEventResult(TOTAL_AMOUNT, 0, null);
+ }
+ return this.#eventBenefit(TOTAL_AMOUNT);
+ }
+
+ #eventBenefit(TOTAL_AMOUNT) {
+ const EVENT_DETAILS = this.#calculateEventDetails();
+ EVENT_DETAILS.giveaway = TOTAL_AMOUNT >= 120000 ? 25000 : 0;
+ const BENEFIT_AMOUNT = Object.values(EVENT_DETAILS).reduce((acc, cur) => acc + cur, 0);
+ this.#printEventResult(TOTAL_AMOUNT, BENEFIT_AMOUNT, EVENT_DETAILS);
+ }
+
+ #calculateTotalOrderAmount() {
+ const calculateTotalOrderAmount = new CalculateTotalOrderAmount();
+ return calculateTotalOrderAmount.result(this.#orderMenu);
+ }
+
+ #calculateEventDetails() {
+ const calculateEventDetails = new CalculateEventDetails();
+ return calculateEventDetails.result(this.#visitDate, this.#orderMenu);
+ }
+
+ #eventBadgeResult(BENEFIT_AMOUNT) {
+ if (BENEFIT_AMOUNT < 5000) {
+ return '์์';
+ }
+ if (BENEFIT_AMOUNT < 10000) {
+ return '๋ณ';
+ }
+ if (BENEFIT_AMOUNT < 20000) {
+ return 'ํธ๋ฆฌ';
+ }
+ return '์ฐํ';
+ }
+
+ #printEventResult(TOTAL_AMOUNT, BENEFIT_AMOUNT, EVENT_DETAILS) {
+ const GIVEAWAY_MENU = TOTAL_AMOUNT >= 120000 ? '์ดํ์ธ 1๊ฐ' : '์์';
+ const EVENT_DETAILS_RESULT = EVENT_DETAILS === null ? '์์' : EVENT_DETAILS;
+ const BENEFIT_AMOUNT_RESULT = BENEFIT_AMOUNT === 0 ? '์์' : BENEFIT_AMOUNT;
+ const DISCOUNT_AMOUNT = TOTAL_AMOUNT >= 120000 ? BENEFIT_AMOUNT - 25000 : BENEFIT_AMOUNT;
+ const EXPECT_PAYMENT_AMOUNT = TOTAL_AMOUNT - DISCOUNT_AMOUNT;
+ const BADGE = this.#eventBadgeResult(BENEFIT_AMOUNT);
+
+ const AMOUNT_RESULT = { TOTAL_AMOUNT, BENEFIT_AMOUNT_RESULT, EXPECT_PAYMENT_AMOUNT };
+ const BENEFIT_RESULT = { GIVEAWAY_MENU, EVENT_DETAILS_RESULT, BADGE };
+ const printEventResult = new PrintEventResult();
+ printEventResult.print(AMOUNT_RESULT, BENEFIT_RESULT);
+ }
+}
+
+export default EventManage; | JavaScript | ์ด ๋ถ๋ถ์์ 10000์ด ์ด๋ค ์๋ฏธ๋ฅผ ๊ฐ๊ณ ์๋์ง ํ๋จํ๊ธฐ ํ๋ญ๋๋ค. ์ด ํ๋ก๋ ์ซ์๊ฐ ํ๋์ฝ๋ฉ ๋ ๊ฒฝ์ฐ๊ฐ ์๋๋ฐ ์๋ฏธ๋ฅผ ๊ฐ์ง ์ ์๋๋ก ์์์ชฝ์ผ๋ก ๋นผ์ฃผ๋ ๊ฒ์ ์ด๋จ๊น์? |
@@ -0,0 +1,67 @@
+import CalculateTotalOrderAmount from '../../model/calculate_total_order_amount.js';
+import CalculateEventDetails from '../../model/calculate_event_details.js';
+import PrintEventResult from '../../view/print_event_result.js';
+
+class EventManage {
+ #visitDate;
+ #orderMenu;
+
+ constructor(visitDate, orderMenu) {
+ this.#visitDate = Number(visitDate);
+ this.#orderMenu = orderMenu;
+ }
+
+ totalOrderAmount() {
+ const TOTAL_AMOUNT = this.#calculateTotalOrderAmount();
+ if (TOTAL_AMOUNT < 10000) {
+ return this.#printEventResult(TOTAL_AMOUNT, 0, null);
+ }
+ return this.#eventBenefit(TOTAL_AMOUNT);
+ }
+
+ #eventBenefit(TOTAL_AMOUNT) {
+ const EVENT_DETAILS = this.#calculateEventDetails();
+ EVENT_DETAILS.giveaway = TOTAL_AMOUNT >= 120000 ? 25000 : 0;
+ const BENEFIT_AMOUNT = Object.values(EVENT_DETAILS).reduce((acc, cur) => acc + cur, 0);
+ this.#printEventResult(TOTAL_AMOUNT, BENEFIT_AMOUNT, EVENT_DETAILS);
+ }
+
+ #calculateTotalOrderAmount() {
+ const calculateTotalOrderAmount = new CalculateTotalOrderAmount();
+ return calculateTotalOrderAmount.result(this.#orderMenu);
+ }
+
+ #calculateEventDetails() {
+ const calculateEventDetails = new CalculateEventDetails();
+ return calculateEventDetails.result(this.#visitDate, this.#orderMenu);
+ }
+
+ #eventBadgeResult(BENEFIT_AMOUNT) {
+ if (BENEFIT_AMOUNT < 5000) {
+ return '์์';
+ }
+ if (BENEFIT_AMOUNT < 10000) {
+ return '๋ณ';
+ }
+ if (BENEFIT_AMOUNT < 20000) {
+ return 'ํธ๋ฆฌ';
+ }
+ return '์ฐํ';
+ }
+
+ #printEventResult(TOTAL_AMOUNT, BENEFIT_AMOUNT, EVENT_DETAILS) {
+ const GIVEAWAY_MENU = TOTAL_AMOUNT >= 120000 ? '์ดํ์ธ 1๊ฐ' : '์์';
+ const EVENT_DETAILS_RESULT = EVENT_DETAILS === null ? '์์' : EVENT_DETAILS;
+ const BENEFIT_AMOUNT_RESULT = BENEFIT_AMOUNT === 0 ? '์์' : BENEFIT_AMOUNT;
+ const DISCOUNT_AMOUNT = TOTAL_AMOUNT >= 120000 ? BENEFIT_AMOUNT - 25000 : BENEFIT_AMOUNT;
+ const EXPECT_PAYMENT_AMOUNT = TOTAL_AMOUNT - DISCOUNT_AMOUNT;
+ const BADGE = this.#eventBadgeResult(BENEFIT_AMOUNT);
+
+ const AMOUNT_RESULT = { TOTAL_AMOUNT, BENEFIT_AMOUNT_RESULT, EXPECT_PAYMENT_AMOUNT };
+ const BENEFIT_RESULT = { GIVEAWAY_MENU, EVENT_DETAILS_RESULT, BADGE };
+ const printEventResult = new PrintEventResult();
+ printEventResult.print(AMOUNT_RESULT, BENEFIT_RESULT);
+ }
+}
+
+export default EventManage; | JavaScript | else๋ฅผ ์ง์ํ๋ผ๊ณ ํ ๊ฒ์ ์๋ฏธ๊ฐ ๊ฑฐ์ ๋น์ทํ ์๋ฏธ๋ฅผ ๊ฐ๊ณ ์๋ ์ผํญ ์ฐ์ฐ์๋ฅผ ์ฐ๋ผ๊ณ ํ ๊ฒ์ ์๋๋ผ๊ณ ์๊ฐํ๋๋ฐ, ์ผํญ ์ฐ์ฐ์๋ฅผ ์ด ์ด์ ๊ฐ ๋ฐ๋ก ์์๊น์? |
@@ -0,0 +1,67 @@
+import CalculateTotalOrderAmount from '../../model/calculate_total_order_amount.js';
+import CalculateEventDetails from '../../model/calculate_event_details.js';
+import PrintEventResult from '../../view/print_event_result.js';
+
+class EventManage {
+ #visitDate;
+ #orderMenu;
+
+ constructor(visitDate, orderMenu) {
+ this.#visitDate = Number(visitDate);
+ this.#orderMenu = orderMenu;
+ }
+
+ totalOrderAmount() {
+ const TOTAL_AMOUNT = this.#calculateTotalOrderAmount();
+ if (TOTAL_AMOUNT < 10000) {
+ return this.#printEventResult(TOTAL_AMOUNT, 0, null);
+ }
+ return this.#eventBenefit(TOTAL_AMOUNT);
+ }
+
+ #eventBenefit(TOTAL_AMOUNT) {
+ const EVENT_DETAILS = this.#calculateEventDetails();
+ EVENT_DETAILS.giveaway = TOTAL_AMOUNT >= 120000 ? 25000 : 0;
+ const BENEFIT_AMOUNT = Object.values(EVENT_DETAILS).reduce((acc, cur) => acc + cur, 0);
+ this.#printEventResult(TOTAL_AMOUNT, BENEFIT_AMOUNT, EVENT_DETAILS);
+ }
+
+ #calculateTotalOrderAmount() {
+ const calculateTotalOrderAmount = new CalculateTotalOrderAmount();
+ return calculateTotalOrderAmount.result(this.#orderMenu);
+ }
+
+ #calculateEventDetails() {
+ const calculateEventDetails = new CalculateEventDetails();
+ return calculateEventDetails.result(this.#visitDate, this.#orderMenu);
+ }
+
+ #eventBadgeResult(BENEFIT_AMOUNT) {
+ if (BENEFIT_AMOUNT < 5000) {
+ return '์์';
+ }
+ if (BENEFIT_AMOUNT < 10000) {
+ return '๋ณ';
+ }
+ if (BENEFIT_AMOUNT < 20000) {
+ return 'ํธ๋ฆฌ';
+ }
+ return '์ฐํ';
+ }
+
+ #printEventResult(TOTAL_AMOUNT, BENEFIT_AMOUNT, EVENT_DETAILS) {
+ const GIVEAWAY_MENU = TOTAL_AMOUNT >= 120000 ? '์ดํ์ธ 1๊ฐ' : '์์';
+ const EVENT_DETAILS_RESULT = EVENT_DETAILS === null ? '์์' : EVENT_DETAILS;
+ const BENEFIT_AMOUNT_RESULT = BENEFIT_AMOUNT === 0 ? '์์' : BENEFIT_AMOUNT;
+ const DISCOUNT_AMOUNT = TOTAL_AMOUNT >= 120000 ? BENEFIT_AMOUNT - 25000 : BENEFIT_AMOUNT;
+ const EXPECT_PAYMENT_AMOUNT = TOTAL_AMOUNT - DISCOUNT_AMOUNT;
+ const BADGE = this.#eventBadgeResult(BENEFIT_AMOUNT);
+
+ const AMOUNT_RESULT = { TOTAL_AMOUNT, BENEFIT_AMOUNT_RESULT, EXPECT_PAYMENT_AMOUNT };
+ const BENEFIT_RESULT = { GIVEAWAY_MENU, EVENT_DETAILS_RESULT, BADGE };
+ const printEventResult = new PrintEventResult();
+ printEventResult.print(AMOUNT_RESULT, BENEFIT_RESULT);
+ }
+}
+
+export default EventManage; | JavaScript | ์
๋ ฅ 2๊ฐ์ ์ด๋ฒคํธ๋ก ํด๋์ค๋ฅผ ๋๋์
จ๋๋ฐ ๋ฐฐ์ง๋ ๋๋จธ์ง ์ชฝ(ํ ์ธ์ด๋ ํํ ๋ฑ ๊ณ์ฐํํธ)์ ๊ธฐ๋ฅ์ด ๋ฌ๋ผ๋ณด์ด๋๋ฐ ๋ค๋ฅธ ํด๋์ค๋ก ๋นผ๋๊ฒ์ ์ด๋จ๊น์ |
@@ -0,0 +1,41 @@
+import VisitDateError from '../../../utils/error/type/visit_date_error.js';
+import printError from '../../../utils/error/print_error.js';
+import INPUT_QUESTION from '../../../utils/constant/input_question.js';
+import OUTPUT from '../../../utils/constant/output.js';
+import InputView from '../../../utils/view_type/InputView.js';
+import OutputView from '../../../utils/view_type/OutputView.js';
+
+class VisitDateManage {
+ #visitDate = null;
+
+ get getVisitDate() {
+ return this.#visitDate;
+ }
+
+ async firstGreeting() {
+ OutputView.printOutput(OUTPUT.FIRST_GREETING);
+ await this.#inputVisitDate();
+ }
+
+ async #inputVisitDate() {
+ while (true) {
+ this.#visitDate = await InputView.userInput(INPUT_QUESTION.VISIT_DATE);
+ if (this.#isValidDate()) {
+ break;
+ }
+ }
+ }
+
+ #isValidDate() {
+ const ERROR = new VisitDateError();
+ try {
+ ERROR.valid(this.#visitDate);
+ return true;
+ } catch (error) {
+ printError(error);
+ return false;
+ }
+ }
+}
+
+export default VisitDateManage; | JavaScript | 3์ฃผ์ฐจ ๊ณตํต ํผ๋๋ฐฑ์ "๊ฐ์ฒด๋ก๋ถํฐ ๋ฐ์ดํฐ๋ฅผ ๊บผ๋ด๋ ๊ฒ(get)์ด ์๋๋ผ, ๋ฉ์์ง๋ฅผ ๋์ง๋๋ก ๊ตฌ์กฐ๋ฅผ ๋ฐ๊ฟ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ง๋ ๊ฐ์ฒด๊ฐ ์ผํ๋๋ก ํด์ผํ๋ค"๊ณ ํ๋๋ฐ, getter๋ฅผ ์ฌ์ฉํ์ง ์๊ณ ํด๊ฒฐํ ๋ฐฉ๋ฒ์ ๊ณ ๋ฏผํด๋ณด๋ ๊ฒ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,41 @@
+import VisitDateError from '../../../utils/error/type/visit_date_error.js';
+import printError from '../../../utils/error/print_error.js';
+import INPUT_QUESTION from '../../../utils/constant/input_question.js';
+import OUTPUT from '../../../utils/constant/output.js';
+import InputView from '../../../utils/view_type/InputView.js';
+import OutputView from '../../../utils/view_type/OutputView.js';
+
+class VisitDateManage {
+ #visitDate = null;
+
+ get getVisitDate() {
+ return this.#visitDate;
+ }
+
+ async firstGreeting() {
+ OutputView.printOutput(OUTPUT.FIRST_GREETING);
+ await this.#inputVisitDate();
+ }
+
+ async #inputVisitDate() {
+ while (true) {
+ this.#visitDate = await InputView.userInput(INPUT_QUESTION.VISIT_DATE);
+ if (this.#isValidDate()) {
+ break;
+ }
+ }
+ }
+
+ #isValidDate() {
+ const ERROR = new VisitDateError();
+ try {
+ ERROR.valid(this.#visitDate);
+ return true;
+ } catch (error) {
+ printError(error);
+ return false;
+ }
+ }
+}
+
+export default VisitDateManage; | JavaScript | ๋ณ์๋ช
์ `ERROR`๋ก ํ์ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค. |
@@ -0,0 +1,41 @@
+import VisitDateError from '../../../utils/error/type/visit_date_error.js';
+import printError from '../../../utils/error/print_error.js';
+import INPUT_QUESTION from '../../../utils/constant/input_question.js';
+import OUTPUT from '../../../utils/constant/output.js';
+import InputView from '../../../utils/view_type/InputView.js';
+import OutputView from '../../../utils/view_type/OutputView.js';
+
+class VisitDateManage {
+ #visitDate = null;
+
+ get getVisitDate() {
+ return this.#visitDate;
+ }
+
+ async firstGreeting() {
+ OutputView.printOutput(OUTPUT.FIRST_GREETING);
+ await this.#inputVisitDate();
+ }
+
+ async #inputVisitDate() {
+ while (true) {
+ this.#visitDate = await InputView.userInput(INPUT_QUESTION.VISIT_DATE);
+ if (this.#isValidDate()) {
+ break;
+ }
+ }
+ }
+
+ #isValidDate() {
+ const ERROR = new VisitDateError();
+ try {
+ ERROR.valid(this.#visitDate);
+ return true;
+ } catch (error) {
+ printError(error);
+ return false;
+ }
+ }
+}
+
+export default VisitDateManage; | JavaScript | (์ง๋๊ฐ๋ค) ์์ธ๊ฐ ๋ฐ์ํ์ฌ `return false`๋ฅผ ํ๋ฉด `#inputVisitDate()` ๋ฉ์๋์์ ์กฐ๊ฑด์์ ๊ฑธ๋ฆฌ์ง ์์ ๊ฒ์ด๊ณ , ๋ฌดํ ๋ฃจํ์ ์ํด ์ฌ์
๋ ฅ์ ๋ฐ๊ฒ๋ ๊ฒ ๊ฐ๋ค์!
๋ฌดํ ๋ฃจํ๊ฐ ์๋ ๋ค๋ฅธ ๋ฐฉ์์ ํด๊ฒฐ๋ฐฉ๋ฒ๋ ๊ณ ๋ฏผํด๋ณด๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,29 @@
+import VisitDateManage from '../child/visit_date_manage.js';
+import OrderMenuManage from '../child/order_menu_manage.js';
+import EventManage from '../child/event_manage.js';
+
+class PlannerManage {
+ #VISIT_DATE = null;
+ #ORDER_MENU = null;
+
+ async visitDate() {
+ const visitDateManage = new VisitDateManage();
+ await visitDateManage.firstGreeting();
+ this.#VISIT_DATE = visitDateManage.getVisitDate;
+ await this.#orderMenu();
+ }
+
+ async #orderMenu() {
+ const orderMenuManage = new OrderMenuManage();
+ await orderMenuManage.inputOrderMenu(this.#VISIT_DATE);
+ this.#ORDER_MENU = orderMenuManage.getOrderMenu;
+ await this.#eventDetails();
+ }
+
+ async #eventDetails() {
+ const eventManage = new EventManage(this.#VISIT_DATE, this.#ORDER_MENU);
+ eventManage.totalOrderAmount();
+ }
+}
+
+export default PlannerManage; | JavaScript | 3์ฃผ์ฐจ ๊ณตํต ํผ๋๋ฐฑ์ ํ๋์ ์๋ฅผ ์ต์ํํ๋ค๋ ์ฝ๋ฉํธ๊ฐ ์๋๋ฐ, ํ๋๋ฅผ ์ฌ์ฉํ์ง ์๊ณ ์ธ์๋ก ์ ํด์ฃผ์ด ์ฌ์ฉํ๋ค๋ฉด ์ด๋ ์๊น์? |
@@ -0,0 +1,29 @@
+import VisitDateManage from '../child/visit_date_manage.js';
+import OrderMenuManage from '../child/order_menu_manage.js';
+import EventManage from '../child/event_manage.js';
+
+class PlannerManage {
+ #VISIT_DATE = null;
+ #ORDER_MENU = null;
+
+ async visitDate() {
+ const visitDateManage = new VisitDateManage();
+ await visitDateManage.firstGreeting();
+ this.#VISIT_DATE = visitDateManage.getVisitDate;
+ await this.#orderMenu();
+ }
+
+ async #orderMenu() {
+ const orderMenuManage = new OrderMenuManage();
+ await orderMenuManage.inputOrderMenu(this.#VISIT_DATE);
+ this.#ORDER_MENU = orderMenuManage.getOrderMenu;
+ await this.#eventDetails();
+ }
+
+ async #eventDetails() {
+ const eventManage = new EventManage(this.#VISIT_DATE, this.#ORDER_MENU);
+ eventManage.totalOrderAmount();
+ }
+}
+
+export default PlannerManage; | JavaScript | ๋๋ฉ์ธ ๋ก์ง๊ณผ UI ๋ก์ง์ด ๋ถ๋ฆฌ๋์ด ์์ง์์ ์ฑ ๋ก์ง์ด ์ ๊ฐ๋๋ค ๋ณด๋ ํฐ ํ๋ฆ์ ํ์
ํ๊ธฐ ์ด๋ ค์๋ณด์
๋๋ค.
PlannerManage์์๋ ํ์ด์ฆ๋ฅผ ๋๋๊ณ ๋ค์ด๋ฐ์ ํตํด ํฐ ํ๋ก์ธ์ค๋ฅผ ํํํ๊ณ , ๋ด๋ถ ๋์์ ๋๋ฉ์ธ, UI ๋ก์ง์ ๋ถ๋ฆฌํ์ฌ ๋ด๋นํ๋๋ก ํ๋ฉด ๋์ฑ ์๋ฏธ๊ฐ ๋๋ฌ๋๊ณ ํ๋ก์ธ์ค๋ฅผ ์ดํดํ๊ธฐ ์์ํ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,67 @@
+import CalculateTotalOrderAmount from '../../model/calculate_total_order_amount.js';
+import CalculateEventDetails from '../../model/calculate_event_details.js';
+import PrintEventResult from '../../view/print_event_result.js';
+
+class EventManage {
+ #visitDate;
+ #orderMenu;
+
+ constructor(visitDate, orderMenu) {
+ this.#visitDate = Number(visitDate);
+ this.#orderMenu = orderMenu;
+ }
+
+ totalOrderAmount() {
+ const TOTAL_AMOUNT = this.#calculateTotalOrderAmount();
+ if (TOTAL_AMOUNT < 10000) {
+ return this.#printEventResult(TOTAL_AMOUNT, 0, null);
+ }
+ return this.#eventBenefit(TOTAL_AMOUNT);
+ }
+
+ #eventBenefit(TOTAL_AMOUNT) {
+ const EVENT_DETAILS = this.#calculateEventDetails();
+ EVENT_DETAILS.giveaway = TOTAL_AMOUNT >= 120000 ? 25000 : 0;
+ const BENEFIT_AMOUNT = Object.values(EVENT_DETAILS).reduce((acc, cur) => acc + cur, 0);
+ this.#printEventResult(TOTAL_AMOUNT, BENEFIT_AMOUNT, EVENT_DETAILS);
+ }
+
+ #calculateTotalOrderAmount() {
+ const calculateTotalOrderAmount = new CalculateTotalOrderAmount();
+ return calculateTotalOrderAmount.result(this.#orderMenu);
+ }
+
+ #calculateEventDetails() {
+ const calculateEventDetails = new CalculateEventDetails();
+ return calculateEventDetails.result(this.#visitDate, this.#orderMenu);
+ }
+
+ #eventBadgeResult(BENEFIT_AMOUNT) {
+ if (BENEFIT_AMOUNT < 5000) {
+ return '์์';
+ }
+ if (BENEFIT_AMOUNT < 10000) {
+ return '๋ณ';
+ }
+ if (BENEFIT_AMOUNT < 20000) {
+ return 'ํธ๋ฆฌ';
+ }
+ return '์ฐํ';
+ }
+
+ #printEventResult(TOTAL_AMOUNT, BENEFIT_AMOUNT, EVENT_DETAILS) {
+ const GIVEAWAY_MENU = TOTAL_AMOUNT >= 120000 ? '์ดํ์ธ 1๊ฐ' : '์์';
+ const EVENT_DETAILS_RESULT = EVENT_DETAILS === null ? '์์' : EVENT_DETAILS;
+ const BENEFIT_AMOUNT_RESULT = BENEFIT_AMOUNT === 0 ? '์์' : BENEFIT_AMOUNT;
+ const DISCOUNT_AMOUNT = TOTAL_AMOUNT >= 120000 ? BENEFIT_AMOUNT - 25000 : BENEFIT_AMOUNT;
+ const EXPECT_PAYMENT_AMOUNT = TOTAL_AMOUNT - DISCOUNT_AMOUNT;
+ const BADGE = this.#eventBadgeResult(BENEFIT_AMOUNT);
+
+ const AMOUNT_RESULT = { TOTAL_AMOUNT, BENEFIT_AMOUNT_RESULT, EXPECT_PAYMENT_AMOUNT };
+ const BENEFIT_RESULT = { GIVEAWAY_MENU, EVENT_DETAILS_RESULT, BADGE };
+ const printEventResult = new PrintEventResult();
+ printEventResult.print(AMOUNT_RESULT, BENEFIT_RESULT);
+ }
+}
+
+export default EventManage; | JavaScript | 10,000๋ ์์๋ก ๊ด๋ฆฌํด์ฃผ๋ฉด ๋์ฑ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. ์๋ฏธ๋ฅผ ํ์
ํ๊ธฐ๋ ์์ํ๊ณ , ๋ง์ฝ ์กฐ๊ฑด์ด ๋ณ๊ฒฝ๋๋ ์ํฉ์ด ์๋ ๊ฒฝ์ฐ ์์ ํ๊ธฐ ์์ํ๋ค๊ณ ์๊ฐํฉ๋๋ค. |
@@ -0,0 +1,67 @@
+import CalculateTotalOrderAmount from '../../model/calculate_total_order_amount.js';
+import CalculateEventDetails from '../../model/calculate_event_details.js';
+import PrintEventResult from '../../view/print_event_result.js';
+
+class EventManage {
+ #visitDate;
+ #orderMenu;
+
+ constructor(visitDate, orderMenu) {
+ this.#visitDate = Number(visitDate);
+ this.#orderMenu = orderMenu;
+ }
+
+ totalOrderAmount() {
+ const TOTAL_AMOUNT = this.#calculateTotalOrderAmount();
+ if (TOTAL_AMOUNT < 10000) {
+ return this.#printEventResult(TOTAL_AMOUNT, 0, null);
+ }
+ return this.#eventBenefit(TOTAL_AMOUNT);
+ }
+
+ #eventBenefit(TOTAL_AMOUNT) {
+ const EVENT_DETAILS = this.#calculateEventDetails();
+ EVENT_DETAILS.giveaway = TOTAL_AMOUNT >= 120000 ? 25000 : 0;
+ const BENEFIT_AMOUNT = Object.values(EVENT_DETAILS).reduce((acc, cur) => acc + cur, 0);
+ this.#printEventResult(TOTAL_AMOUNT, BENEFIT_AMOUNT, EVENT_DETAILS);
+ }
+
+ #calculateTotalOrderAmount() {
+ const calculateTotalOrderAmount = new CalculateTotalOrderAmount();
+ return calculateTotalOrderAmount.result(this.#orderMenu);
+ }
+
+ #calculateEventDetails() {
+ const calculateEventDetails = new CalculateEventDetails();
+ return calculateEventDetails.result(this.#visitDate, this.#orderMenu);
+ }
+
+ #eventBadgeResult(BENEFIT_AMOUNT) {
+ if (BENEFIT_AMOUNT < 5000) {
+ return '์์';
+ }
+ if (BENEFIT_AMOUNT < 10000) {
+ return '๋ณ';
+ }
+ if (BENEFIT_AMOUNT < 20000) {
+ return 'ํธ๋ฆฌ';
+ }
+ return '์ฐํ';
+ }
+
+ #printEventResult(TOTAL_AMOUNT, BENEFIT_AMOUNT, EVENT_DETAILS) {
+ const GIVEAWAY_MENU = TOTAL_AMOUNT >= 120000 ? '์ดํ์ธ 1๊ฐ' : '์์';
+ const EVENT_DETAILS_RESULT = EVENT_DETAILS === null ? '์์' : EVENT_DETAILS;
+ const BENEFIT_AMOUNT_RESULT = BENEFIT_AMOUNT === 0 ? '์์' : BENEFIT_AMOUNT;
+ const DISCOUNT_AMOUNT = TOTAL_AMOUNT >= 120000 ? BENEFIT_AMOUNT - 25000 : BENEFIT_AMOUNT;
+ const EXPECT_PAYMENT_AMOUNT = TOTAL_AMOUNT - DISCOUNT_AMOUNT;
+ const BADGE = this.#eventBadgeResult(BENEFIT_AMOUNT);
+
+ const AMOUNT_RESULT = { TOTAL_AMOUNT, BENEFIT_AMOUNT_RESULT, EXPECT_PAYMENT_AMOUNT };
+ const BENEFIT_RESULT = { GIVEAWAY_MENU, EVENT_DETAILS_RESULT, BADGE };
+ const printEventResult = new PrintEventResult();
+ printEventResult.print(AMOUNT_RESULT, BENEFIT_RESULT);
+ }
+}
+
+export default EventManage; | JavaScript | ์ฌ์ํ์ง๋ง, ์กฐ๊ฑด์ ์ญ์์ผ๋ก ์ ์๋ค๋ฉด ๋ ์ดํดํ๊ธฐ ์์ํ ๊ฒ ๊ฐ์ต๋๋ค.
`20000 ์ด์: ์ฐํ / 10000 ์ด์: ํธ๋ฆฌ / 5000 ์ด์: ๋ณ / ๋๋จธ์ง: ์์` |
@@ -0,0 +1,28 @@
+const EVENT_NAMES = ['ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ', 'ํ์ผ ํ ์ธ', '์ฃผ๋ง ํ ์ธ', 'ํน๋ณ ํ ์ธ', '์ฆ์ ์ด๋ฒคํธ'];
+
+const WEEKDAY_DISCOUNT_DATE = [
+ 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 17,
+ 18, 19, 20, 21, 24, 25, 26, 27, 28, 31,
+];
+
+const WEEKEND_DISCOUNT_DATE = [
+ 1, 2, 8, 9, 15, 16, 22, 23, 29, 30,
+];
+
+const SPECIAL_DISCOUNT_DATE = [
+ 3, 10, 17, 24, 25, 31,
+];
+
+Object.freeze(
+ EVENT_NAMES,
+ WEEKDAY_DISCOUNT_DATE,
+ WEEKEND_DISCOUNT_DATE,
+ SPECIAL_DISCOUNT_DATE,
+);
+
+export {
+ EVENT_NAMES,
+ WEEKDAY_DISCOUNT_DATE,
+ WEEKEND_DISCOUNT_DATE,
+ SPECIAL_DISCOUNT_DATE,
+}; | JavaScript | ์ฌ๋ฌ ๊ฐ์ ์ธ์๋ฅผ ๋๊ฒจ์ฃผ๊ณ freeze ๋ฉ์๋๋ฅผ ํธ์ถํ๋ฉด ํ๋ฆฌ์ง๋์ง ์์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,33 @@
+const MENU_NAMES = [
+ '์์ก์ด์ํ', 'ํํ์ค', '์์ ์๋ฌ๋',
+ 'ํฐ๋ณธ์คํ
์ดํฌ', '๋ฐ๋นํ๋ฆฝ', 'ํด์ฐ๋ฌผํ์คํ', 'ํฌ๋ฆฌ์ค๋ง์คํ์คํ',
+ '์ด์ฝ์ผ์ดํฌ', '์์ด์คํฌ๋ฆผ',
+ '์ ๋ก์ฝ๋ผ', '๋ ๋์์ธ', '์ดํ์ธ',
+];
+
+const MENUS = {
+ Epitizer: {
+ ์์ก์ด์ํ: 6000,
+ ํํ์ค: 5500,
+ ์์ ์๋ฌ๋: 8000,
+ },
+ Main: {
+ ํฐ๋ณธ์คํ
์ดํฌ: 55000,
+ ๋ฐ๋นํ๋ฆฝ: 54000,
+ ํด์ฐ๋ฌผํ์คํ: 35000,
+ ํฌ๋ฆฌ์ค๋ง์คํ์คํ: 25000,
+ },
+ Dessert: {
+ ์ด์ฝ์ผ์ดํฌ: 15000,
+ ์์ด์คํฌ๋ฆผ: 5000,
+ },
+ Drink: {
+ ์ ๋ก์ฝ๋ผ: 3000,
+ ๋ ๋์์ธ: 60000,
+ ์ดํ์ธ: 25000,
+ },
+};
+
+Object.freeze(MENU_NAMES, MENUS);
+
+export { MENU_NAMES, MENUS }; | JavaScript | ์ค์ฒฉ๋ ๊ฐ์ฒด์ ๊ฒฝ์ฐ, ์ธ๋ถ๋ฅผ ํ๋ฆฌ์ง ํด์ฃผ์ด๋ ๋ด๋ถ๋ ํ๋ฆฌ์ง ๋์ง ์์ต๋๋ค. deep freeze ํค์๋๋ก ํ์ตํด๋ณด๋ ๊ฒ์ ์ถ์ฒ๋๋ฆฝ๋๋ค. |
@@ -0,0 +1,31 @@
+package dto;
+
+import domain.car.Car;
+
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import static util.Splitter.BLANK;
+
+public class CarDto {
+ private String name;
+ private List<String> whiteSpaceList;
+
+ public CarDto(Car car) {
+ assert car != null;
+ this.name = car.getName();
+ this.whiteSpaceList = IntStream.range(0, car.getPosition())
+ .mapToObj(num -> BLANK)
+ .collect(Collectors.toList());
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public List<String> getWhiteSpaceList() {
+ return whiteSpaceList;
+ }
+
+} | Java | carDto์ position์ ์์ฑ์์์ whiteSpaceList ๋ง๋๋ ๊ฑธ ์ ์ธํ๊ณค ์ฐ๋๋ฐ๊ฐ ์๋ ๊ฒ ๊ฐ์๋ฐ, carDto์์ ๋นผ๋ ๊ฑด ์ด๋ป๊ฒ ์๊ฐํ์๋์? |
@@ -1,79 +1,83 @@
<!DOCTYPE html>
<html>
+
<head>
-<meta charset="UTF-8">
-<title>๋ ์ด์ค!</title>
+ <meta charset="UTF-8">
+ <title>๋ ์ด์ค!</title>
-<!-- Latest compiled and minified CSS -->
-<link rel="stylesheet"
- href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
- integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
- crossorigin="anonymous">
+ <!-- Latest compiled and minified CSS -->
+ <link rel="stylesheet"
+ href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
+ integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
+ crossorigin="anonymous">
-<!-- Optional theme -->
-<link rel="stylesheet"
- href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
- integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp"
- crossorigin="anonymous">
+ <!-- Optional theme -->
+ <link rel="stylesheet"
+ href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
+ integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp"
+ crossorigin="anonymous">
-<!-- Latest compiled and minified JavaScript -->
-<script
- src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
- integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
- crossorigin="anonymous"></script>
-<style>
-body {
- padding-top: 40px;
- padding-bottom: 40px;
- background-color: #eee;
-}
+ <!-- Latest compiled and minified JavaScript -->
+ <script
+ src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
+ integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
+ crossorigin="anonymous"></script>
+ <style>
+ body {
+ padding-top: 40px;
+ padding-bottom: 40px;
+ background-color: #eee;
+ }
-.form-lotto {
- max-width: 1000px;
- padding: 15px;
- margin: 0 auto;
-}
+ .form-lotto {
+ max-width: 1000px;
+ padding: 15px;
+ margin: 0 auto;
+ }
-.form-lotto .form-control {
- position: relative;
- height: auto;
- -webkit-box-sizing: border-box;
- -moz-box-sizing: border-box;
- box-sizing: border-box;
- padding: 10px;
- font-size: 16px;
-}
+ .form-lotto .form-control {
+ position: relative;
+ height: auto;
+ -webkit-box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;
+ padding: 10px;
+ font-size: 16px;
+ }
-.submit-button {
- margin-top: 10px;
-}
-</style>
+ .submit-button {
+ margin-top: 10px;
+ }
+ </style>
</head>
<body>
- <div class="container">
+<div class="container">
<div class="row">
- <div class="col-md-12">
+ <div class="col-md-12">
- <h2 class="text-center">๋ฐ์ง๊ฐ ๋์น๋ ์๋์ฐจ ๋ ์ด์ฑ ๊ฒ์ with Pobi</h2>
- <div class="form-show-div" class="form-group">
- <h3>๊ฒฐ๊ณผ์
๋๋ค</h3>
- (์ด๋ฆ๋ง๋ค ๋์ด์ฐ๊ธฐ๋ก ๊ตฌ๋ถํด ์ฃผ์ธ์.)
- <div id="standings">๋ฐ์ฌ์ฑ : 🚌</div>
- <div id="standings">์ค์ง์ : 🚌</div>
- <div id="standings">์ ํธ์ : 🚌</div>
- <div id="standings">๊น์ : 🚌</div>
- <br />
- <div>๋ฐ์ฌ์ฑ, ์ ํธ์์ด ์ฐ์นํ์ต๋๋ค.</div>
+ <h2 class="text-center">๋ฐ์ง๊ฐ ๋์น๋ ์๋์ฐจ ๋ ์ด์ฑ ๊ฒ์ with Pobi</h2>
+ <div class="form-show-div" class="form-group">
+ <h3>๊ฒฐ๊ณผ์
๋๋ค</h3>
+ (์ด๋ฆ๋ง๋ค ๋์ด์ฐ๊ธฐ๋ก ๊ตฌ๋ถํด ์ฃผ์ธ์.)
+ {{#cars}}
+ <div id="standings">{{name}} : {{#whiteSpaceList}} {{/whiteSpaceList}}🚌</div>
+ {{/cars}}
+ <br/>
+ <div>{{#winners}}
+ {{#if @last}}
+ {{this}}
+ {{else}}
+ {{this}},
+ {{/if}}
+ {{/winners}}์ด ์ฐ์นํ์ต๋๋ค.</div>
+ </div>
</div>
- </div>
</div>
- </div>
+</div>
</body>
-<script src="/js/race.js">
-</script>
</html>
\ No newline at end of file | Unknown | ์ด ๋ถ๋ถ์ ์ด๋ป๊ฒ ํ ๊น ๊ณ ๋ฏผํ๋ค๊ฐ..๊ทธ๋ฅ ๋ฌธ๊ตฌ๋ฅผ ์์ ํ๋๋ฐ, ์ด ๋ถ๊ธฐ๋ฌธ ๋ฃ๋ ๊ฒ๋ ์๊ฐํด๋ด์ผ๊ฒ ๋ค์๐ |
@@ -0,0 +1,79 @@
+package view;
+
+import domain.car.Car;
+import domain.game.RacingGame;
+import domain.game.Track;
+import domain.random.RandomGenerator;
+import domain.strategy.RandomMovingStrategy;
+import dto.CarDto;
+import dto.RacingGameRequestDto;
+import spark.Route;
+import util.Splitter;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Random;
+
+import static java.util.stream.Collectors.toList;
+import static util.RenderUtil.render;
+import static util.Splitter.COMMA;
+
+public class WebRacingHandler {
+ public Route handleGetName() {
+ return (req, res) -> {
+ HashMap<String, Object> model = new HashMap<>();
+ String names = req.queryParams("names");
+
+ List<String> splitNames = Splitter.splitBlank(names);
+ model.put("names", splitNames);
+ model.put("nameStrings", String.join(COMMA, splitNames));
+ return render(model, "/game.html");
+ };
+ }
+
+ public Route handleResult() {
+ return (req, res) -> {
+ final HashMap<String, Object> model = new HashMap<>();
+ final RacingGameRequestDto racingGameRequestDto = new RacingGameRequestDto(Integer.parseInt(req.queryParams("turn")), req.queryParams("names"));
+
+ final RacingGame racingGame = generateRacingGame(racingGameRequestDto);
+
+ finishGame(racingGame);
+ Track track = racingGame.getTrack();
+
+ List<CarDto> carDtos = mapToCarDto(track);
+ List<String> nameOfWinners = mapToName(racingGame);
+
+
+ model.put("cars", carDtos);
+ model.put("winners", nameOfWinners);
+ return render(model, "/result.html");
+ };
+ }
+
+ private void finishGame(RacingGame racingGame) {
+ while (!racingGame.isDone()) {
+ racingGame.proceedOneTurn();
+ }
+ }
+
+ private RacingGame generateRacingGame(RacingGameRequestDto racingGameRequestDto) {
+ final Random generate = RandomGenerator.generate();
+ final RandomMovingStrategy movingStrategy = new RandomMovingStrategy(generate);
+ return RacingGame.newInstance(racingGameRequestDto.getNames(), racingGameRequestDto.getTurn(), movingStrategy);
+ }
+
+ private List<String> mapToName(RacingGame racingGame) {
+ return racingGame.getWinner()
+ .stream()
+ .map(Car::getName)
+ .collect(toList());
+ }
+
+ private List<CarDto> mapToCarDto(Track track) {
+ return track.getCars()
+ .stream()
+ .map(CarDto::new)
+ .collect(toList());
+ }
+} | Java | ๊ฒ์์์์ ํ์ํ input๊ณผ ๊ฒฐ๊ณผ๊ฐ์ธ result๋ฅผ ๊ฐ์ ธ์ค๋ ๋ก์ง์ ๋ฉ์๋๋ก ๋ถ๋ฆฌํ๋ฉด ๋ ๊น๋ํด ์ง๊ฑฐ ๊ฐ์์ |
@@ -0,0 +1,79 @@
+package view;
+
+import domain.car.Car;
+import domain.game.RacingGame;
+import domain.game.Track;
+import domain.random.RandomGenerator;
+import domain.strategy.RandomMovingStrategy;
+import dto.CarDto;
+import dto.RacingGameRequestDto;
+import spark.Route;
+import util.Splitter;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Random;
+
+import static java.util.stream.Collectors.toList;
+import static util.RenderUtil.render;
+import static util.Splitter.COMMA;
+
+public class WebRacingHandler {
+ public Route handleGetName() {
+ return (req, res) -> {
+ HashMap<String, Object> model = new HashMap<>();
+ String names = req.queryParams("names");
+
+ List<String> splitNames = Splitter.splitBlank(names);
+ model.put("names", splitNames);
+ model.put("nameStrings", String.join(COMMA, splitNames));
+ return render(model, "/game.html");
+ };
+ }
+
+ public Route handleResult() {
+ return (req, res) -> {
+ final HashMap<String, Object> model = new HashMap<>();
+ final RacingGameRequestDto racingGameRequestDto = new RacingGameRequestDto(Integer.parseInt(req.queryParams("turn")), req.queryParams("names"));
+
+ final RacingGame racingGame = generateRacingGame(racingGameRequestDto);
+
+ finishGame(racingGame);
+ Track track = racingGame.getTrack();
+
+ List<CarDto> carDtos = mapToCarDto(track);
+ List<String> nameOfWinners = mapToName(racingGame);
+
+
+ model.put("cars", carDtos);
+ model.put("winners", nameOfWinners);
+ return render(model, "/result.html");
+ };
+ }
+
+ private void finishGame(RacingGame racingGame) {
+ while (!racingGame.isDone()) {
+ racingGame.proceedOneTurn();
+ }
+ }
+
+ private RacingGame generateRacingGame(RacingGameRequestDto racingGameRequestDto) {
+ final Random generate = RandomGenerator.generate();
+ final RandomMovingStrategy movingStrategy = new RandomMovingStrategy(generate);
+ return RacingGame.newInstance(racingGameRequestDto.getNames(), racingGameRequestDto.getTurn(), movingStrategy);
+ }
+
+ private List<String> mapToName(RacingGame racingGame) {
+ return racingGame.getWinner()
+ .stream()
+ .map(Car::getName)
+ .collect(toList());
+ }
+
+ private List<CarDto> mapToCarDto(Track track) {
+ return track.getCars()
+ .stream()
+ .map(CarDto::new)
+ .collect(toList());
+ }
+} | Java | ๋ฉ์๋๋ฅผ ๋ถํดํด๋ ์ข์๊ฒ ๊ฐ์ต๋๋ค ๐ ! |
@@ -0,0 +1,25 @@
+import view.WebRacingHandler;
+
+import java.util.HashMap;
+
+import static spark.Spark.*;
+import static util.RenderUtil.render;
+
+public class WebMain {
+ public static final int PORT = 8080;
+ private static WebRacingHandler webRacingHandler = new WebRacingHandler();
+
+ public static void main(String[] args) {
+ port(PORT);
+
+ get("/", (req, res) -> render(new HashMap<>(), "/index.html"));
+
+ post("/name", webRacingHandler.handleGetName());
+
+ post("/result", webRacingHandler.handleResult());
+ }
+
+
+
+
+}
\ No newline at end of file | Java | ํ, ๋ณ๊ฑด์๋๋ฐ `post`๊ฐ ์๊ตฌ์ฌํญ์ด์์ต๋๋ค ๐ |
@@ -0,0 +1,79 @@
+package view;
+
+import domain.car.Car;
+import domain.game.RacingGame;
+import domain.game.Track;
+import domain.random.RandomGenerator;
+import domain.strategy.RandomMovingStrategy;
+import dto.CarDto;
+import dto.RacingGameRequestDto;
+import spark.Route;
+import util.Splitter;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Random;
+
+import static java.util.stream.Collectors.toList;
+import static util.RenderUtil.render;
+import static util.Splitter.COMMA;
+
+public class WebRacingHandler {
+ public Route handleGetName() {
+ return (req, res) -> {
+ HashMap<String, Object> model = new HashMap<>();
+ String names = req.queryParams("names");
+
+ List<String> splitNames = Splitter.splitBlank(names);
+ model.put("names", splitNames);
+ model.put("nameStrings", String.join(COMMA, splitNames));
+ return render(model, "/game.html");
+ };
+ }
+
+ public Route handleResult() {
+ return (req, res) -> {
+ final HashMap<String, Object> model = new HashMap<>();
+ final RacingGameRequestDto racingGameRequestDto = new RacingGameRequestDto(Integer.parseInt(req.queryParams("turn")), req.queryParams("names"));
+
+ final RacingGame racingGame = generateRacingGame(racingGameRequestDto);
+
+ finishGame(racingGame);
+ Track track = racingGame.getTrack();
+
+ List<CarDto> carDtos = mapToCarDto(track);
+ List<String> nameOfWinners = mapToName(racingGame);
+
+
+ model.put("cars", carDtos);
+ model.put("winners", nameOfWinners);
+ return render(model, "/result.html");
+ };
+ }
+
+ private void finishGame(RacingGame racingGame) {
+ while (!racingGame.isDone()) {
+ racingGame.proceedOneTurn();
+ }
+ }
+
+ private RacingGame generateRacingGame(RacingGameRequestDto racingGameRequestDto) {
+ final Random generate = RandomGenerator.generate();
+ final RandomMovingStrategy movingStrategy = new RandomMovingStrategy(generate);
+ return RacingGame.newInstance(racingGameRequestDto.getNames(), racingGameRequestDto.getTurn(), movingStrategy);
+ }
+
+ private List<String> mapToName(RacingGame racingGame) {
+ return racingGame.getWinner()
+ .stream()
+ .map(Car::getName)
+ .collect(toList());
+ }
+
+ private List<CarDto> mapToCarDto(Track track) {
+ return track.getCars()
+ .stream()
+ .map(CarDto::new)
+ .collect(toList());
+ }
+} | Java | ์๊ฑด ๋ฐํ๊ฐ์ด ๋ฐ๋ก ์๋์ด์ ๊ฐ ์์๊น์ ?
`getTracks()`๋ ๋ฉ์๋๊ฐ ๋ฐ๋ก์์ด์์! |
@@ -0,0 +1,79 @@
+package view;
+
+import domain.car.Car;
+import domain.game.RacingGame;
+import domain.game.Track;
+import domain.random.RandomGenerator;
+import domain.strategy.RandomMovingStrategy;
+import dto.CarDto;
+import dto.RacingGameRequestDto;
+import spark.Route;
+import util.Splitter;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Random;
+
+import static java.util.stream.Collectors.toList;
+import static util.RenderUtil.render;
+import static util.Splitter.COMMA;
+
+public class WebRacingHandler {
+ public Route handleGetName() {
+ return (req, res) -> {
+ HashMap<String, Object> model = new HashMap<>();
+ String names = req.queryParams("names");
+
+ List<String> splitNames = Splitter.splitBlank(names);
+ model.put("names", splitNames);
+ model.put("nameStrings", String.join(COMMA, splitNames));
+ return render(model, "/game.html");
+ };
+ }
+
+ public Route handleResult() {
+ return (req, res) -> {
+ final HashMap<String, Object> model = new HashMap<>();
+ final RacingGameRequestDto racingGameRequestDto = new RacingGameRequestDto(Integer.parseInt(req.queryParams("turn")), req.queryParams("names"));
+
+ final RacingGame racingGame = generateRacingGame(racingGameRequestDto);
+
+ finishGame(racingGame);
+ Track track = racingGame.getTrack();
+
+ List<CarDto> carDtos = mapToCarDto(track);
+ List<String> nameOfWinners = mapToName(racingGame);
+
+
+ model.put("cars", carDtos);
+ model.put("winners", nameOfWinners);
+ return render(model, "/result.html");
+ };
+ }
+
+ private void finishGame(RacingGame racingGame) {
+ while (!racingGame.isDone()) {
+ racingGame.proceedOneTurn();
+ }
+ }
+
+ private RacingGame generateRacingGame(RacingGameRequestDto racingGameRequestDto) {
+ final Random generate = RandomGenerator.generate();
+ final RandomMovingStrategy movingStrategy = new RandomMovingStrategy(generate);
+ return RacingGame.newInstance(racingGameRequestDto.getNames(), racingGameRequestDto.getTurn(), movingStrategy);
+ }
+
+ private List<String> mapToName(RacingGame racingGame) {
+ return racingGame.getWinner()
+ .stream()
+ .map(Car::getName)
+ .collect(toList());
+ }
+
+ private List<CarDto> mapToCarDto(Track track) {
+ return track.getCars()
+ .stream()
+ .map(CarDto::new)
+ .collect(toList());
+ }
+} | 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๋ฉ์๋๋ค์ ์ ๋ถ ๋ชจ์์ฃผ๋๊ฒ๋ ํ๋์ ๋ฐฉ๋ฒ์ผ ๊ฒ ๊ฐ์์
printWelcomeMessage();
Date date = dateController.acceptVisitDate();
Bill bill = orderController.acceptOrder();
Reward reward = eventController.confirmReward(date, bill);
RewardDto rewardDto = reward.toDto();
printRewardResult(rewardDto);
printOrderResult(date, bill);
printFinalCheckoutPrice(bill, rewardDto);
printBadgeResult(badgeController.grantBadge(rewardDto));
์ด๋ฐ์์ผ๋ก์ |
@@ -0,0 +1,26 @@
+package christmas.domain.category;
+
+import christmas.domain.menu.Menu;
+import christmas.domain.menu.MenuItem;
+
+public enum Appetizer implements MenuItem {
+ MUSHROOM_SOUP("์์ก์ด์ํ", 6000),
+ TAPAS("ํํ์ค", 5500),
+ CAESAR_SALAD("์์ ์๋ฌ๋", 8000);
+
+ private Menu menu;
+
+ Appetizer(String name, int price) {
+ this.menu = new Menu(name, price);
+ }
+ @Override
+ public Menu get(){
+ return menu;
+ }
+
+ @Override
+ public String getName() {
+ return menu.name();
+ }
+
+} | Java | ์ธํฐํ์ด์ค๋ฅผ ์ฌ์ฉํ์
จ๊ตฐ์!! ์ด๋ ๊ฒ ๋๋ฉด ์ ์ง ๋ณด์์ ๋ ์ข์๊ฑฐ๋ผ๋ ์๊ฐ์ด ๋๋ค์ ๋ฉ์ ธ์ |
@@ -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 | ์ ๋ ๋ฆฌ๋ทฐํ๋ค๊ฐ ๋ฐฐ์ด ๋ด์ฉ์ธ๋ฐ localDate.of() ๋ฅผ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ๋ ์์ด์ ์ถ์ฒ ๋๋ ค์!! |
@@ -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 | static import๋ฌธ๋ค์ด ์์ ์์นํ๋ ๊ฒ์ด ์๋ฐ ์ปจ๋ฒค์
์ ๋ถํฉํ๋ ๊ฒ์ผ๋ก ์๊ณ ์์ด์ |
@@ -0,0 +1,14 @@
+package christmas.controller;
+
+import christmas.domain.date.Date;
+import christmas.domain.reward.Reward;
+import christmas.domain.order.Bill;
+import christmas.factory.ServiceFactory;
+import christmas.service.EventService;
+
+public class EventController {
+ private final EventService eventService = ServiceFactory.getEventService();
+ public Reward confirmReward(Date date, Bill bill){
+ return eventService.createReward(date,bill);
+ }
+} | Java | ํ์ค ๊ณต๋ฐฑ ์ฝ์
์ด ๋น ์ง ๊ฒ ๊ฐ์์ |
@@ -0,0 +1,28 @@
+package christmas.domain.event.discount;
+
+import java.util.List;
+
+import christmas.domain.date.Date;
+import christmas.domain.reward.DiscountEventReward;
+import christmas.lib.event.DiscountEvent;
+
+import static christmas.constant.EventConstant.SPECIAL_DAY_MESSAGE;
+import static christmas.constant.EventConstant.SPECIAL_DAY_PRICE;
+
+public class SpecialDiscountEvent extends DiscountEvent<Void> {
+ private final List<Integer> SPECIAL_DAY = List.of(3, 10, 17, 24, 25, 31);
+ private final String EVENT_NAME = SPECIAL_DAY_MESSAGE;
+
+ @Override
+ public boolean checkCondition(Date date) {
+ if (SPECIAL_DAY.contains(date.day())) {
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public DiscountEventReward provideReward(Void object) {
+ return new DiscountEventReward(EVENT_NAME, SPECIAL_DAY_PRICE);
+ }
+} | Java | ํน๋ณ ํ ์ธ์ด ์ ์ฉ๋๋ ๋ ์ด ๋งค์ฃผ ์ผ์์ผ, ํฌ๋ฆฌ์ค๋ง์ค ๋ ์ด๋ผ๋ ์ ์ DayOfWeek๋ฅผ ํ์ฉํด์ ํํํ๋ ๊ฒ๋ ์ข์ ๋ฐฉ๋ฒ์ผ๊ฑฐ ๊ฐ์์! |
@@ -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 | record๋ฅผ ํ์ฉํด์ผ๊ฒ ๋ค๊ณ ์๊ฐํ ์ด์ ๊ฐ ์์๊น์? |
@@ -0,0 +1,27 @@
+package christmas.domain.category;
+
+import christmas.domain.menu.Menu;
+import christmas.domain.menu.MenuItem;
+
+public enum Dessert implements MenuItem {
+ CHOCO_CAKE("์ด์ฝ์ผ์ดํฌ", 15000),
+ ICE_CREAM("์์ด์คํฌ๋ฆผ", 5000);
+
+ private Menu menu;
+
+ Dessert(String name, int price) {
+ this.menu = new Menu(name, price);
+ }
+
+ @Override
+ public Menu get() {
+ return menu;
+ }
+
+ @Override
+ public String getName() {
+ return menu.name();
+ }
+
+
+} | Java | ๋ฉ๋ด ์นดํ
๊ณ ๋ฆฌ๋ง๋ค enum ํด๋์ค๋ฅผ ๋๋ ์๊ฐ์ ๋ชปํ๋๋ฐ ์ด๋ ๊ฒ ํ๋ฉด ์ ์ง๋ณด์๊ฐ ๋ ์ฝ๊ฒ ๋ค์!
์ข์ ์์ด๋์ด์ธ๊ฑฐ ๊ฐ์์! |
@@ -0,0 +1,6 @@
+package christmas.constant;
+
+public interface DateConstant {
+ public static int START_DAY = 1;
+ public static int END_DAY = 31;
+} | Java | ์ด ๋ถ๋ถ๋ ์ ์๊ฐ ๋ฐ๋๋ค๋ฉด?
12์์์ 1์๋ก ๋ฐ๋ ๋, 2์๋ก ๋ฐ๋ ๋ ์ผ์์ ๋ํ ์ ์ฝ์กฐ๊ฑด์ ์๋์ผ๋ก ์์ ํด์ฃผ์ด์ผ ํ ๊ฒ์ผ๋ก ์๊ฒฌ๋ฉ๋๋ค.
์ ์ญ์์ ์ค์ ํ๋ ์ฐ/์ ์ค์ ์ ๋ฐํ์ผ๋ก StartDay์ EndDay๋ฅผ ๋์ ์ผ๋ก ํ๋จํ๋ฉด ์ข์ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,9 @@
+package christmas.constant;
+
+public interface OrderConstant {
+ public static final String ORDER_SEPARATOR = ",";
+ public static final String REQUEST_SEPARATOR = "-";
+
+ public static final int MIN_AMOUNT = 1;
+ public static final int MAX_TOTAL_ORDER_COUNT = 20;
+} | Java | ์ด ๋ถ๋ถ๋ ์ ์ฝ์กฐ๊ฑด์ผ๋ก ๋ถ๋ฆฌํด์ ์ค์ ํ ๋ถ๋ถ ๋๋ฌด ์ข์ต๋๋ค ๐ |
@@ -0,0 +1,26 @@
+package christmas.domain.category;
+
+import christmas.domain.menu.Menu;
+import christmas.domain.menu.MenuItem;
+
+public enum Drink implements MenuItem {
+ ZERO_COKE("์ ๋ก์ฝ๋ผ", 3000),
+ RED_WINE("๋ ๋์์ธ", 60000),
+ CHAMPAGNE("์ดํ์ธ", 25000);
+ private Menu menu;
+
+ Drink(String name, int price) {
+ this.menu = new Menu(name, price);
+ }
+
+ @Override
+ public Menu get() {
+ return menu;
+ }
+
+ @Override
+ public String getName() {
+ return menu.name();
+ }
+
+} | Java | ์ด ๋ถ๋ถ๋ 25_000๊ณผ ๊ฐ์ด ์ผ๊ด์ ์ธ ํํ๋ก ์ฌ์ฉํ๋ฉด ์ข์ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,28 @@
+package christmas.domain.event.discount;
+
+import java.util.List;
+
+import christmas.domain.date.Date;
+import christmas.domain.reward.DiscountEventReward;
+import christmas.lib.event.DiscountEvent;
+
+import static christmas.constant.EventConstant.SPECIAL_DAY_MESSAGE;
+import static christmas.constant.EventConstant.SPECIAL_DAY_PRICE;
+
+public class SpecialDiscountEvent extends DiscountEvent<Void> {
+ private final List<Integer> SPECIAL_DAY = List.of(3, 10, 17, 24, 25, 31);
+ private final String EVENT_NAME = SPECIAL_DAY_MESSAGE;
+
+ @Override
+ public boolean checkCondition(Date date) {
+ if (SPECIAL_DAY.contains(date.day())) {
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public DiscountEventReward provideReward(Void object) {
+ return new DiscountEventReward(EVENT_NAME, SPECIAL_DAY_PRICE);
+ }
+} | Java | ์ ๋ ์ด ๋ถ๋ถ์ ๋ํด์๋ ๋ค๋ฅธ ์๊ฒฌ์
๋๋ค!
`๋ณ` ์ด ๋ฌ๋ ค์๋ ๋ ์ด ์ด๋ฒคํธ ๋ ๋ก ์ ์ฉํ๋ค๋ ์กฐ๊ฑด์ด์๊ธฐ ๋๋ฌธ์,
์ด ๋ถ๋ถ์ List๋ก ์ ์ ์ผ๋ก ํ ๋นํด์ฃผ๋๊ฒ ์คํ๋ ค ๋ ์ ์ ํ ์ค๊ณ์๋ค๊ณ ์๊ฐํด์! |
@@ -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,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 | calculateTotalPrice์ ๋ฆฌํดํ์ Integer์ธ๋ฐ, ๋ฐํ ๋ณ์๋ int๋ค์!
ํด๋น ๋ฉ์๋๋ฅผ Integer๋ก ๋ฐํํ๋๋ก ์ค๊ณํ์ ์ด์ ๊ฐ ์์๊น์? |
@@ -0,0 +1,9 @@
+package christmas.constant;
+
+public interface BadgeConstant {
+ public static final int SANTA_THRESHOLD = 20000;
+ public static final int TREE_THRESHOLD = 10000;
+ public static final int STAR_THRESHOLD = 5000;
+ public static final int NON_THRESHOLD = 0;
+
+} | Java | ํ์ฌ ๊ตฌํํ์ ์ฝ๋์์ `BadgeConstant` ๋ `Badge` enum ์์ ์์๋ก ๋ฐ์ ์ฌ์ฉ๋์ง ์์ ๊ฒ์ผ๋ก ์กฐ๊ธ ๋ถํ์ํ ์ธํฐํ์ด์ค์ง ์๋ ์๊ฐ์ด๋ญ๋๋ค. `Badge` enum ์์ ์ด ๋ถ๋ถ์ ํจ๊ป ๊ตฌํํ ์ ์๋ค๊ณ ์๊ฐํ๋๋ฐ ์ด๋ป๊ฒ ์๊ฐํ์๋์? |
@@ -0,0 +1,27 @@
+package christmas.constant;
+
+import christmas.domain.category.Drink;
+import christmas.domain.menu.Menu;
+
+public interface EventConstant {
+ public static final Integer EVENT_THRESHOLD_PRICE = 10000;
+
+ public static final Integer WEEKEND_DISCOUNT_PRICE = 2023;
+ public static final String WEEKEND_DISCOUNT_EVENT_MESSAGE = "์ฃผ๋ง ํ ์ธ";
+
+ public static final Integer WEEKDAY_DISCOUNT_PRICE = 2023;
+ public static final String WEEKDAY_DISCOUNT_EVENT_MESSAGE = "ํ์ผ ํ ์ธ";
+
+
+ public static final Integer D_DAY_DISCOUNT_UNIT = 100;
+ public static final Integer D_DAY_START_PRICE = 1000;
+ public static final Integer CHRISTMAS_DAY = 25;
+ public static final String CHRISTMAS_EVENT_MESSAGE = "ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ";
+
+ public static final Integer SPECIAL_DAY_PRICE = 1000;
+ public static final String SPECIAL_DAY_MESSAGE = "ํน๋ณ ํ ์ธ";
+
+
+ public static final Integer CHAMPAGNE_LIMIT_PRICE = 120000;
+ public static final Menu CHAMPAGNE_PRESENT = Drink.CHAMPAGNE.get();
+} | Java | ์ด๋ฒคํธ ๊ด๋ จ ์์๋ฅผ ์ ๋ enum ์ผ๋ก ๊ตฌํํ์ต๋๋ค. ์ธํฐํ์ด์ค๋ก ์์๋ค์ ์ ์ํ์ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค! |
@@ -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 | ๋ ์ง ์ ๋ณด๋ฅผ ๋ด์ ๋ถ๋ณ๊ฐ์ฒด๋ฅผ ์ด์ฉํ์
จ๊ตฐ์ ๐ ๋ค๋ง ํ์ฌ `Date` ๊ฐ์ฒด๋ ๋ ์ง ์ ๋ณด์ ์์ผ ์ ๋ณด๋ง ๊ฐ์ง๊ณ ์๋๊ฒ์ผ๋ก ๋ณด์ด๋๋ฐ ๊ทธ๋ ๋ค๋ฉด ์ด๋ฏธ ์๋ฐ์์ ์ ๊ณตํ๋ `LocalDate` ๋ฅผ ์ฌ์ฉํ๋๊ฒ ์ด๋จ๊น ํ๋ ์๊ฐ์ด ๋ญ๋๋ค! 1์ฃผ์ฐจ ํผ๋๋ฐฑ์๋ ๋์ค๋ ๋ด์ฉ์ด๋๊น ๊ณ ๋ คํด๋ณด์๋ฉด ์ข์๊ฒ ๊ฐ์ต๋๋ค ๐ |
@@ -0,0 +1,25 @@
+package christmas.domain.event;
+
+import christmas.lib.event.DiscountEvent;
+import christmas.lib.event.Event;
+import christmas.lib.event.PresentEvent;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public record InProgressEventList(List<DiscountEvent> discountEventList,
+ List<PresentEvent> presentEventList) {
+ public static InProgressEventList of(List<Event> eventList) {
+ List<DiscountEvent> discountEventList = new ArrayList<>();
+ List<PresentEvent> presentEventList = new ArrayList<>();
+ for (Event event : eventList) {
+ if (event instanceof DiscountEvent) {
+ discountEventList.add((DiscountEvent) event);
+ }
+ if (event instanceof PresentEvent) {
+ presentEventList.add((PresentEvent) event);
+ }
+ }
+ return new InProgressEventList(discountEventList, presentEventList);
+ }
+} | Java | ์ด ๋ถ๋ถ์ ์ฝ๊ฐ ๊ฐ์ ํ ์๋ ์์๊ฒ ๊ฐ์ต๋๋ค! ์ด ํด๋์ค์ `of` ๋ฉ์๋๋ `EventSercice` ์์ `EventFactory` ์ static ๋ณ์์ธ `EVENT_LIST` ๋ฅผ ํ๋ผ๋ฏธํฐ๋ก ๋ฃ์ด์ ์์ฑํ๋ ๋ถ๋ถ์์๋ง ์ฐ์ด๋๋ฐ `EVENT_LIST` ๋ ํญ์ ๊ฐ์ ๊ฐ์ ๊ฐ์ง๋ ๋ณ์๋ก ์์๋ฉ๋๋ค. ๊ทธ๋ ๋ค๋ฉด ์ฒ์๋ถํฐ ํ ์ธ ์ด๋ฒคํธ์ ์ฆ์ ์ด๋ฒคํธ๋ฅผ ๋ฐ๋ก ๊ด๋ฆฌํ๋ ๋ฐฉ๋ฒ์ ์ด๋จ๊น์? |
@@ -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,25 @@
+package com.example.chatgptcodereviewtest.controller;
+
+import com.example.chatgptcodereviewtest.dto.InputDto;
+import com.example.chatgptcodereviewtest.service.TestService;
+import lombok.RequiredArgsConstructor;
+import org.springframework.web.bind.annotation.*;
+
+/**
+ * ์ค๋ช
:
+ *
+ * @author ์ตํ๋ฒ(Jayce) / hb.choi@dreamus.io
+ * @since 2023/03/23
+ */
+@RestController
+@RequestMapping("/test")
+@RequiredArgsConstructor
+public class TestController {
+
+ private final TestService testService;
+
+ @PostMapping
+ public int convertText(@RequestBody InputDto inputDto) {
+ return testService.addAgeAndNameLength(inputDto);
+ }
+} | Java | ์ ์ฝ๋ ์กฐ๊ฐ์์๋ `TestController` ํด๋์ค๋ฅผ ์ ์ํ๊ณ ์์ผ๋ฉฐ, ํด๋น ์ปจํธ๋กค๋ฌ์ `convertText` ๋ฉ์๋๋ `InputDto` ๊ฐ์ฒด๋ฅผ ๋ฐ์๋ค์ฌ `testService`์์ `addAgeAndNameLength` ๋ฉ์๋๋ฅผ ํธ์ถํ ๊ฒฐ๊ณผ๋ฅผ ๋ฐํํฉ๋๋ค.
์ด ์ฝ๋ ์กฐ๊ฐ์ ๋ํ ์ฃผ์ ๊ฐ์ ์ ์์ ๋ค์๊ณผ ๊ฐ์ต๋๋ค:
1. ์ปจํธ๋กค๋ฌ์ ์๋น์ค ํด๋์ค์ ์ด๋ฆ์ ๋ ๋ช
ํํ๊ฒ ๋ํ๋ผ ์ ์๋๋ก ๋ณ๊ฒฝํ๋ ๊ฒ์ด ์ข์ต๋๋ค.
2. ์ปจํธ๋กค๋ฌ์์ ์ฌ์ฉ๋ ๊ฒฝ๋ก๋ช
(`"/test"`) ๋ฐ HTTP ๋ฉ์๋(`@PostMapping`)์ ๋ํด ์ถฉ๋ถํ ์ค๋ช
์ด ์์ผ๋ฏ๋ก API์ ์๋๋ฅผ ๋ ์ ์ค๋ช
ํ ํ์๊ฐ ์์ต๋๋ค.
3. `InputDto` ํด๋์ค์ ํ๋ ์ ํจ์ฑ ๊ฒ์ฌ๋ฅผ ์ํ ๊ฒ์ฆ ์ด๋
ธํ
์ด์
๋ฑ์ ์ถ๊ฐ์ ์ธ ๋ฒจ๋ฆฌ๋ฐ์ด์
๋ก์ง์ด ํ์ํฉ๋๋ค.
๋ฌธ์ ์ ์ผ๋ก๋ ํ์ฌ ์ฝ๋ ์ํ์ ๋ฌธ๋ฒ์ ์ธ ์ค๋ฅ๋ ๊ธฐ๋ฅ์์ ํฐ ์ํ์ ๋ณด์ด์ง ์์ต๋๋ค. |
@@ -0,0 +1,22 @@
+package com.example.chatgptcodereviewtest.dto;
+
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.ToString;
+
+/**
+ * ์ค๋ช
:
+ *
+ * @author ์ตํ๋ฒ(Jayce) / hb.choi@dreamus.io
+ * @since 2023/03/23
+ */
+@Getter
+@ToString
+@NoArgsConstructor
+@AllArgsConstructor
+public class InputDto {
+
+ private String name;
+ private int age;
+} | Java | ์ ์ฝ๋๋ lombok ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ด์ฉํด InputDto ํด๋์ค๋ฅผ ์์ฑํ๊ณ ์๋ ๊ฒ์ผ๋ก ๋ณด์
๋๋ค.
๊ฐ์ ์ :
1. ํด๋์ค์ ๋ณ์ ์ด๋ฆ์ ๋ ๋ช
ํํ๊ฒ ์ ์ด์ฃผ๋ฉด ์ข๊ฒ ์ต๋๋ค.
2. Setter๊ฐ ์๊ธฐ ๋๋ฌธ์ name๊ณผ age์ ๋ํ ์ผ๋ถ ์ ๋ณด ๋ณ๊ฒฝ์ด ๋ถ๊ฐ๋ฅํฉ๋๋ค. ๋ฐ๋ผ์, ํด๋น DTO๋ฅผ ์ฌ์ฉํ๋ ํด๋์ค์์ ์ ์ดํ ์ ์๋๋ก Setter ๋ฉ์๋ ์ถ๊ฐ๋ฅผ ๊ณ ๋ คํด๋ณผ ํ์์ฑ์ด ์์ต๋๋ค.
๋ฒ๊ทธ ๊ฐ๋ฅ์ฑ:
ํ์ฌ ํด๋น ์ฝ๋์์ ๋ฒ๊ทธ๋ ๋ณด์ด์ง ์์ต๋๋ค. |
@@ -0,0 +1,20 @@
+package com.example.chatgptcodereviewtest.service;
+
+import com.example.chatgptcodereviewtest.dto.InputDto;
+import org.springframework.stereotype.Service;
+
+/**
+ * ์ค๋ช
:
+ *
+ * @author ์ตํ๋ฒ(Jayce) / hb.choi@dreamus.io
+ * @since 2023/03/23
+ */
+@Service
+public class TestService {
+
+ public int addAgeAndNameLength(InputDto inputDto) {
+ int age = inputDto.getAge();
+ int nameLength = inputDto.getName().length();
+ return age + nameLength;
+ }
+} | Java | ์์ ์ฝ๋ ๋ฆฌ๋ทฐ์ ๋ํ ์ ์๊ฐ์
๋๋ค.
๊ธฐ๋ฅ์ ์ผ๋ก ๋ฌธ์ ๊ฐ ์์ด ๋ณด์ด๋ฉฐ, ์ถ๊ฐ ๊ฐ์ ์ฌํญ์ ์์ต๋๋ค. ๊ทธ๋ฌ๋ ๋ช ๊ฐ์ง ์์ ์์ ์ฌํญ์ ์ ์ํด ๋๋ฆฌ๊ฒ ์ต๋๋ค:
- ์ฃผ์์ด ์์ธํ์ง ์์ ๋ณ๊ฒฝ ๋ ํ๋ก์ ํธ์ ๋ํด ์ถฉ๋ถํ ์ค๋ช
์ ์ ๊ณตํ์ง ์์ต๋๋ค. ๋ฉ์๋ ์ด๋ฆ 'addAgeAndNameLength' ์์ฒด๊ฐ ๊ธฐ๋ฅ์ ์ค๋ช
ํ๋ ๋ฐ ๋งค์ฐ ํฌ๊ด์ ์
๋๋ค. ์ข ๋ ๊ตฌ์ฒด์ ์ธ ๋ฉ์๋ ๋ฐ ํด๋์ค ์ค๋ช
๊ณผ ํจ๊ป ์ฃผ์์ ์ถ๊ฐํ๋ ๊ฒ์ด ์ข์ต๋๋ค.
- ๋ชจ๋ ์์ธ๋ฅผ ์ฒ๋ฆฌ ํ ์ ์๋๋ก try-catch ๋ธ๋ก์ ์ถ๊ฐํ ์ ์์ต๋๋ค.
์์ธกํ ์์๋ ๊ฐ์ ์ ๋ฌํ์ฌ ์ถ๋ ฅ ๊ฐ์ด ์์๊ฐ๋๋ ๊ฒฝ์ฐ ๋ฑ ์ํ์ฑ์ด ์๋ ๊ธฐ๋ฅ์ ์์ผ๋ฉฐ, ๊ธฐ๋ณธ ์ ๋ ํ
์คํธ๋ฅผ ์์ฑํ์ฌ ์ฝ๋์ ์ ํ์ฑ์ ๊ฒ์ฆํ๋ ๊ฒ์ด ์ข์ต๋๋ค. |
@@ -0,0 +1,49 @@
+package lotto.domain;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+public class LottoGame {
+ private static final int TICKET_PRICE = 1000;
+
+ List<LottoTicket> lottoTickets;
+ LottoMatch lottoMatch;
+
+ public LottoGame() {
+ this.lottoTickets = new ArrayList<>();
+ }
+
+ public List<LottoTicket> buyLottoTicket(int money) {
+ int ticketNum = money / TICKET_PRICE;
+
+ for (int i = 0; i < ticketNum; i++) {
+ this.lottoTickets.add(new LottoTicket());
+ }
+
+ return this.lottoTickets;
+ }
+
+ public HashMap<LottoMatchNumber, Integer> winLotto() {
+ return this.lottoMatch.matchResult(lottoTickets);
+ }
+
+ public void inputTargetNumbers(String input) {
+ lottoMatch = new LottoMatch(input);
+ }
+
+
+ public double checkIncome(HashMap<LottoMatchNumber, Integer> results, int money){
+ double income = 0;
+
+ int totalIncome = 0;
+ for (LottoMatchNumber lottoMatchNumber : LottoMatchNumber.values()) {
+ totalIncome += lottoMatchNumber.totalPrizeMoney(results.get(lottoMatchNumber));
+ }
+
+ income = (double) totalIncome/money;
+
+ return income;
+ }
+
+} | Java | ์ ๊ทผ ์ ํ์๋ฅผ ๋ถ์ด๋๊ฒ ์ข์ ๊ฒ ๊ฐ๋ค์. |
@@ -0,0 +1,28 @@
+package lotto.domain;
+
+import stringcalculator.Operation;
+
+public enum LottoMatchNumber {
+ MATCH3(3, 5000) {int totalPrizeMoney(int count) {return prizeMoney * count;}},
+ MATCH4(4, 50000) {int totalPrizeMoney(int count) {return prizeMoney * count;}},
+ MATCH5(5, 1500000) {int totalPrizeMoney(int count) {return prizeMoney * count;}},
+ MATCH6(6, 2000000000) {int totalPrizeMoney(int count) {return prizeMoney * count;}};
+
+ private final int matchNumber;
+ protected final int prizeMoney;
+ abstract int totalPrizeMoney(int count);
+
+ LottoMatchNumber(int matchNumber, int prizeMoney) {
+ this.matchNumber = matchNumber;
+ this.prizeMoney = prizeMoney;
+ }
+
+ public int getMatchNumber() {
+ return matchNumber;
+ }
+
+ @Override
+ public String toString() {
+ return matchNumber + "๊ฐ ์ผ์น (" + prizeMoney + "์)";
+ }
+} | Java | enum๋ ๋น์ฆ๋์ค ๋ก์ง์ ์ผ๋ถ์ด๋ฏ๋ก view ๋ถ๋ถ์ ๊ตฌํ์ enum์ ๋๋๊ฑด ์ข์ง ์์ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,28 @@
+package lotto.domain;
+
+import stringcalculator.Operation;
+
+public enum LottoMatchNumber {
+ MATCH3(3, 5000) {int totalPrizeMoney(int count) {return prizeMoney * count;}},
+ MATCH4(4, 50000) {int totalPrizeMoney(int count) {return prizeMoney * count;}},
+ MATCH5(5, 1500000) {int totalPrizeMoney(int count) {return prizeMoney * count;}},
+ MATCH6(6, 2000000000) {int totalPrizeMoney(int count) {return prizeMoney * count;}};
+
+ private final int matchNumber;
+ protected final int prizeMoney;
+ abstract int totalPrizeMoney(int count);
+
+ LottoMatchNumber(int matchNumber, int prizeMoney) {
+ this.matchNumber = matchNumber;
+ this.prizeMoney = prizeMoney;
+ }
+
+ public int getMatchNumber() {
+ return matchNumber;
+ }
+
+ @Override
+ public String toString() {
+ return matchNumber + "๊ฐ ์ผ์น (" + prizeMoney + "์)";
+ }
+} | Java | ๋ฑ์๋ณ๋ก ๋ชจ๋ ๋์ผํ ๊ตฌํ์ฒด๋ฅผ ๊ฐ์ง ๊ฒ ๊ฐ์๋ฐ์. ์ถ์ ๋ฉ์๋๋ก ์ ์๋ ํ์๊ฐ ์๋์ง ๊ณ ๋ฏผ์ด ํ์ํด๋ณด์ฌ์.
๊ทธ๋ฆฌ๊ณ ํ์ฌ ๋ก๋ ๋๋ฉ์ธ์์ enum์ด ๋ก๋์ ๋ฑ์๋ณ ๊ฐ์ ๋ฐ ๋น์ฒจ ๊ธ์ก์ ๋ํ๋ด๋ ์ญํ ์ ํ๊ณ ์์ต๋๋ค. ๊ณ ์ ๋ ์์๋ค๋ง ๊ฐ์ง๋๊ฒ ์๋๋ผ ๋ฐ์ ๊ฐ์๋งํผ ๊ณฑํด์ ๊ณ์ฐํด์ฃผ๋ ์ญํ ์ ๊ฐ์ง๋๊ฒ ์ ์ ํ ์ง๋ ๊ณ ๋ฏผํด๋ณด์๋ฉด ์ข๊ฒ ๋ค์. |
@@ -0,0 +1,49 @@
+package lotto.domain;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+public class LottoGame {
+ private static final int TICKET_PRICE = 1000;
+
+ List<LottoTicket> lottoTickets;
+ LottoMatch lottoMatch;
+
+ public LottoGame() {
+ this.lottoTickets = new ArrayList<>();
+ }
+
+ public List<LottoTicket> buyLottoTicket(int money) {
+ int ticketNum = money / TICKET_PRICE;
+
+ for (int i = 0; i < ticketNum; i++) {
+ this.lottoTickets.add(new LottoTicket());
+ }
+
+ return this.lottoTickets;
+ }
+
+ public HashMap<LottoMatchNumber, Integer> winLotto() {
+ return this.lottoMatch.matchResult(lottoTickets);
+ }
+
+ public void inputTargetNumbers(String input) {
+ lottoMatch = new LottoMatch(input);
+ }
+
+
+ public double checkIncome(HashMap<LottoMatchNumber, Integer> results, int money){
+ double income = 0;
+
+ int totalIncome = 0;
+ for (LottoMatchNumber lottoMatchNumber : LottoMatchNumber.values()) {
+ totalIncome += lottoMatchNumber.totalPrizeMoney(results.get(lottoMatchNumber));
+ }
+
+ income = (double) totalIncome/money;
+
+ return income;
+ }
+
+} | Java | ์ค์ํ ๋ถ๋ถ์ ์๋์ง๋ง Stream.generate๋ฅผ ํตํด ๋ถ๋ณ ํํ๋ก ํํํ ์ ์์ ๊ฒ ๊ฐ๋ค์. ๊ฐ๋ณ๋ณด๋ค๋ ๋ถ๋ณ ํํ๋ก ํํํ๋๊ฒ ์ฌ์ด๋ ์ดํํธ๋ ์ ๊ณ ๊ฐ๋
์ฑ ์ธก๋ฉด์์๋ ์ข์ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,49 @@
+package lotto.domain;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+public class LottoGame {
+ private static final int TICKET_PRICE = 1000;
+
+ List<LottoTicket> lottoTickets;
+ LottoMatch lottoMatch;
+
+ public LottoGame() {
+ this.lottoTickets = new ArrayList<>();
+ }
+
+ public List<LottoTicket> buyLottoTicket(int money) {
+ int ticketNum = money / TICKET_PRICE;
+
+ for (int i = 0; i < ticketNum; i++) {
+ this.lottoTickets.add(new LottoTicket());
+ }
+
+ return this.lottoTickets;
+ }
+
+ public HashMap<LottoMatchNumber, Integer> winLotto() {
+ return this.lottoMatch.matchResult(lottoTickets);
+ }
+
+ public void inputTargetNumbers(String input) {
+ lottoMatch = new LottoMatch(input);
+ }
+
+
+ public double checkIncome(HashMap<LottoMatchNumber, Integer> results, int money){
+ double income = 0;
+
+ int totalIncome = 0;
+ for (LottoMatchNumber lottoMatchNumber : LottoMatchNumber.values()) {
+ totalIncome += lottoMatchNumber.totalPrizeMoney(results.get(lottoMatchNumber));
+ }
+
+ income = (double) totalIncome/money;
+
+ return income;
+ }
+
+} | Java | ์ผ๋ฐ์ ์ผ๋ก ๋ฉ์๋ ๋ฆฌํด ํ์
์ด๋ ํ๋ผ๋ฏธํฐ ๋ฑ์ ๋คํ์ฑ ์ธก๋ฉด์์ ์ด์ ์ด ์๊ธฐ ๋๋ฌธ์ ๊ตฌ์ฒด ํ์
(HashMap)์ ์ฌ์ฉํ์ง ์์ต๋๋ค. ์ด์ ๊ฐ ์๋๊ฒ ์๋๋ผ๋ฉด ์ธํฐํ์ด์ค์ธ Map์ ๋ฆฌํด ํ์
์ผ๋ก ์ฐ์๋๊ฒ ์ด๋จ๊น์? |
@@ -0,0 +1,49 @@
+package lotto.domain;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+public class LottoGame {
+ private static final int TICKET_PRICE = 1000;
+
+ List<LottoTicket> lottoTickets;
+ LottoMatch lottoMatch;
+
+ public LottoGame() {
+ this.lottoTickets = new ArrayList<>();
+ }
+
+ public List<LottoTicket> buyLottoTicket(int money) {
+ int ticketNum = money / TICKET_PRICE;
+
+ for (int i = 0; i < ticketNum; i++) {
+ this.lottoTickets.add(new LottoTicket());
+ }
+
+ return this.lottoTickets;
+ }
+
+ public HashMap<LottoMatchNumber, Integer> winLotto() {
+ return this.lottoMatch.matchResult(lottoTickets);
+ }
+
+ public void inputTargetNumbers(String input) {
+ lottoMatch = new LottoMatch(input);
+ }
+
+
+ public double checkIncome(HashMap<LottoMatchNumber, Integer> results, int money){
+ double income = 0;
+
+ int totalIncome = 0;
+ for (LottoMatchNumber lottoMatchNumber : LottoMatchNumber.values()) {
+ totalIncome += lottoMatchNumber.totalPrizeMoney(results.get(lottoMatchNumber));
+ }
+
+ income = (double) totalIncome/money;
+
+ return income;
+ }
+
+} | Java | ์ด๋ฐ ํํ๋ก ์ฌ์ฉํ ๊ฑฐ๋ฉด ์ธ์คํด์ค ๋ณ์ ์์ด ๋ฐ๋ก ๋ฆฌํดํ๋ ํํ๋ก ์ฌ์ฉํ๋ฉด ์ด๋จ๊น์? |
@@ -0,0 +1,47 @@
+package lotto.domain;
+
+
+import java.util.*;
+
+public class LottoMatch {
+
+ List<Integer> targetNumbers;
+
+
+ public LottoMatch(String input) {
+ targetNumbers = new ArrayList<>();
+ String[] inputs = input.split(", ");
+
+ for (int i = 0; i < inputs.length; i++) {
+ targetNumbers.add(Integer.valueOf(inputs[i]));
+ }
+ }
+
+ public HashMap<LottoMatchNumber, Integer> matchResult(List<LottoTicket> myNumbers) {
+ HashMap<LottoMatchNumber, Integer> results = new HashMap<>();
+ results.put(LottoMatchNumber.MATCH3, 0);
+ results.put(LottoMatchNumber.MATCH4, 0);
+ results.put(LottoMatchNumber.MATCH5, 0);
+ results.put(LottoMatchNumber.MATCH6, 0);
+
+ for (LottoTicket myNumber : myNumbers) {
+ int matchCount = myNumber.checkMatch(targetNumbers);
+ inputMatchResult(matchCount, results);
+ }
+
+ return results;
+ }
+
+ private void inputMatchResult(int matchCount, HashMap<LottoMatchNumber, Integer> results) {
+ for (LottoMatchNumber lottoMatchNumber : LottoMatchNumber.values()) {
+ inputMatchCount(matchCount, results, lottoMatchNumber);
+ }
+ }
+
+ private void inputMatchCount(int matchCount, HashMap<LottoMatchNumber, Integer> results, LottoMatchNumber lottoMatchNumber) {
+ if (lottoMatchNumber.getMatchNumber() == matchCount) {
+ results.put(lottoMatchNumber, results.get(lottoMatchNumber) + 1);
+ }
+ }
+
+} | Java | Stream์ groupingBy๋ Function.identity๋ฅผ ํ์ฉํด๋ณด์๋ ์ข์ ๊ฒ ๊ฐ๋ค์. |
@@ -0,0 +1,47 @@
+package lotto.domain;
+
+
+import java.util.*;
+
+public class LottoMatch {
+
+ List<Integer> targetNumbers;
+
+
+ public LottoMatch(String input) {
+ targetNumbers = new ArrayList<>();
+ String[] inputs = input.split(", ");
+
+ for (int i = 0; i < inputs.length; i++) {
+ targetNumbers.add(Integer.valueOf(inputs[i]));
+ }
+ }
+
+ public HashMap<LottoMatchNumber, Integer> matchResult(List<LottoTicket> myNumbers) {
+ HashMap<LottoMatchNumber, Integer> results = new HashMap<>();
+ results.put(LottoMatchNumber.MATCH3, 0);
+ results.put(LottoMatchNumber.MATCH4, 0);
+ results.put(LottoMatchNumber.MATCH5, 0);
+ results.put(LottoMatchNumber.MATCH6, 0);
+
+ for (LottoTicket myNumber : myNumbers) {
+ int matchCount = myNumber.checkMatch(targetNumbers);
+ inputMatchResult(matchCount, results);
+ }
+
+ return results;
+ }
+
+ private void inputMatchResult(int matchCount, HashMap<LottoMatchNumber, Integer> results) {
+ for (LottoMatchNumber lottoMatchNumber : LottoMatchNumber.values()) {
+ inputMatchCount(matchCount, results, lottoMatchNumber);
+ }
+ }
+
+ private void inputMatchCount(int matchCount, HashMap<LottoMatchNumber, Integer> results, LottoMatchNumber lottoMatchNumber) {
+ if (lottoMatchNumber.getMatchNumber() == matchCount) {
+ results.put(lottoMatchNumber, results.get(lottoMatchNumber) + 1);
+ }
+ }
+
+} | Java | ์์ฑ์๋ ์ด๋ฏธ ์์ฑ์ด๋ ์ฑ
์์ ๊ฐ์ง๊ณ ์๋๋ฐ ์์ฑ์ ๋ด๋ถ์์ split์ ํตํ ํ์ฑ ๋ฐ ์ฌ๋ฌ ์ฑ
์์ด ํฌํจ๋์ด ์๋ค์.
์์ฑ์์ ๋ก์ง์ ๋ฃ๊ณ ์ถ๋ค๋ฉด ์ ์ ํฉํฐ๋ฆฌ๋ก ๋ถ๋ฆฌํ๊ณ ์ ์ ํฉํฐ๋ฆฌ์ ๋ก์ง์ ์ถ๊ฐํ ๋ค ๊ฑฐ๊ธฐ์ ์์ฑ์๋ฅผ ํธ์ถํ๊ฑฐ๋ ํ๋ ํํ๋ก ๊ตฌํํ๋๊ฑด ์ด๋จ๊น์? |
@@ -0,0 +1,65 @@
+package lotto.domain;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+public class LottoTicket {
+
+ private static final int PICK_NUMBERS = 6;
+
+ List<Integer> lottoNumbers;
+
+ public LottoTicket() {
+ this.lottoNumbers = new ArrayList<>();
+ for (int i = 1; i <= 45; i++) {
+ this.lottoNumbers.add(i);
+ }
+ lottoNumbers = issueTicket();
+ }
+
+ public LottoTicket(List<Integer> ticketNumbers) {
+ this.lottoNumbers = new ArrayList<>(ticketNumbers);
+ }
+
+ public List<Integer> issueTicket() {
+ Collections.shuffle(this.lottoNumbers);
+ this.lottoNumbers = this.lottoNumbers.subList(0, PICK_NUMBERS);
+ Collections.sort(this.lottoNumbers);
+
+ return this.lottoNumbers;
+ }
+
+
+ public int checkMatch(List<Integer> targetNumbers) {
+ if (targetNumbers.size() != this.lottoNumbers.size()) {
+ throw new IllegalArgumentException("๋น์ฒจ ๋ฒํธ ๊ฐ์๊ฐ ์ผ์น ํ์ง ์์ต๋๋ค.");
+ }
+
+ int count = 0;
+ for (int i = 0; i < this.lottoNumbers.size(); i++) {
+ count = compareTargetnumbers(targetNumbers, i, count);
+ }
+
+ return count;
+ }
+
+ private int compareTargetnumbers(List<Integer> targetNumbers, int i, int count) {
+ for (int j = 0; j < targetNumbers.size(); j++) {
+ count = compareNumbers(targetNumbers, i, count, j);
+ }
+ return count;
+ }
+
+ private int compareNumbers(List<Integer> targetNumbers, int i, int count, int j) {
+ if (this.lottoNumbers.get(i) == targetNumbers.get(j)) {
+ count++;
+ }
+ return count;
+ }
+
+ @Override
+ public String toString() {
+ return lottoNumbers.toString();
+ }
+} | Java | ์ ์ฝ ์กฐ๊ฑด ๊ฒ์ฆ์ด ์ ํ ํฌํจ๋์ด ์์ง ์๋ค์. ๋๋ฉ์ธ์ ํน์ฑ์ ์ ๋ํ๋ด์ง ๋ชปํ๋ ๊ฒ ๊ฐ์ต๋๋ค.
1. 1 - 45๊น์ง์ ์ซ์๋ง ์กด์ฌํด์ผ ํจ
2. 6๊ฐ์ ์ค๋ณต๋์ง ์์ ์ซ์๋ก ์ด๋ฃจ์ด์ ธ์ผ ํจ
์์ ๊ฐ์ด ๋ก๋ ๋๋ฉ์ธ์ ํน์ฑ์ด ํด๋์ค์ ๋ฐ์๋๋๋ก ์ค๊ณํด๋ณด์๋ฉด ์ข๊ฒ ์ต๋๋ค. |
@@ -0,0 +1,39 @@
+package nextstep.auth.authentication;
+
+import nextstep.member.application.UserDetailsService;
+import nextstep.member.domain.User;
+import org.springframework.web.servlet.HandlerInterceptor;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+public abstract class Authenticator implements HandlerInterceptor {
+
+ private final UserDetailsService userDetailsService;
+
+ public Authenticator(UserDetailsService userDetailsService) {
+ this.userDetailsService = userDetailsService;
+ }
+
+ @Override
+ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
+ AuthenticationToken token = convert(request);
+ User user = userDetailsService.loadUserByUsername(token.getPrincipal());
+
+ checkAuthentication(user, token.getCredentials());
+ authenticate(user, response);
+
+ return false;
+ }
+
+ abstract public AuthenticationToken convert(HttpServletRequest request) throws IOException;
+
+ abstract public void authenticate(User user, HttpServletResponse response) throws IOException;
+
+ private void checkAuthentication(User user, String password) {
+ if (!user.checkPassword(password)) {
+ throw new AuthenticationException();
+ }
+ }
+} | Java | ์๋ ์๊ตฌ์ฌํญ์ด ๋ฐ์๋์ง ์์ ๊ฒ ๊ฐ์์ ๐ข
<img width="516" alt="แแ
ณแแ
ณแ
แ
ตแซแแ
ฃแบ 2022-08-16 แแ
ฉแแ
ฎ 10 07 08" src="https://user-images.githubusercontent.com/17218212/184886987-febc108f-8b2f-403b-a53e-bf36f069cc24.png"> |
@@ -1,51 +1,45 @@
package nextstep.auth.token;
import com.fasterxml.jackson.databind.ObjectMapper;
-import nextstep.auth.authentication.AuthenticationException;
-import nextstep.member.application.LoginMemberService;
-import nextstep.member.domain.LoginMember;
+import nextstep.auth.authentication.AuthenticationToken;
+import nextstep.auth.authentication.Authenticator;
+import nextstep.member.application.UserDetailsService;
+import nextstep.member.domain.User;
import org.springframework.http.MediaType;
-import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
import java.util.stream.Collectors;
-public class TokenAuthenticationInterceptor implements HandlerInterceptor {
- private LoginMemberService loginMemberService;
- private JwtTokenProvider jwtTokenProvider;
+public class TokenAuthenticationInterceptor extends Authenticator {
+ private final JwtTokenProvider jwtTokenProvider;
+ private final ObjectMapper objectMapper = new ObjectMapper();
- public TokenAuthenticationInterceptor(LoginMemberService loginMemberService, JwtTokenProvider jwtTokenProvider) {
- this.loginMemberService = loginMemberService;
+ public TokenAuthenticationInterceptor(UserDetailsService userDetailsService, JwtTokenProvider jwtTokenProvider) {
+ super(userDetailsService);
this.jwtTokenProvider = jwtTokenProvider;
}
@Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
+ public AuthenticationToken convert(HttpServletRequest request) throws IOException {
String content = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
TokenRequest tokenRequest = new ObjectMapper().readValue(content, TokenRequest.class);
String principal = tokenRequest.getEmail();
String credentials = tokenRequest.getPassword();
- LoginMember loginMember = loginMemberService.loadUserByUsername(principal);
-
- if (loginMember == null) {
- throw new AuthenticationException();
- }
-
- if (!loginMember.checkPassword(credentials)) {
- throw new AuthenticationException();
- }
+ return new AuthenticationToken(principal, credentials);
+ }
- String token = jwtTokenProvider.createToken(loginMember.getEmail(), loginMember.getAuthorities());
+ @Override
+ public void authenticate(User member, HttpServletResponse response) throws IOException {
+ String token = jwtTokenProvider.createToken(member.getEmail(), member.getAuthorities());
TokenResponse tokenResponse = new TokenResponse(token);
- String responseToClient = new ObjectMapper().writeValueAsString(tokenResponse);
+ String responseToClient = objectMapper.writeValueAsString(tokenResponse);
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getOutputStream().print(responseToClient);
-
- return false;
}
} | Java | `ObjectMapper` ๋ ์์ฑ ๋น์ฉ์ด ๋น์ธ๋ค๊ณ ์๋ ค์ง ๊ฐ์ฒด์
๋๋ค. ์์กด์ฑ ์ฃผ์
์ ํตํด ํด๊ฒฐํด๋ณผ ์ ์์๊น์? ๐ |
@@ -0,0 +1,8 @@
+package nextstep.member.application;
+
+import nextstep.member.domain.User;
+
+public interface UserDetailsService {
+
+ User loadUserByUsername(String email);
+} | Java | ์ด ์ธํฐํ์ด์ค๊ฐ `member` ํจํค์ง์ ์๋๊ฒ ๋ง์๊น์? ๐ค |
@@ -0,0 +1,83 @@
+package nextstep.subway.unit;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import nextstep.auth.authentication.AuthenticationToken;
+import nextstep.auth.authentication.LoginMember;
+import nextstep.auth.token.JwtTokenProvider;
+import nextstep.auth.token.TokenAuthenticationInterceptor;
+import nextstep.auth.token.TokenRequest;
+import nextstep.auth.token.TokenResponse;
+import nextstep.member.application.UserDetailsService;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.http.HttpStatus;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.BDDMockito.given;
+import static org.mockito.Mockito.when;
+
+@ExtendWith({MockitoExtension.class})
+class TokenAuthenticationInterceptorMockTest {
+ private static final String EMAIL = "email@email.com";
+ private static final String PASSWORD = "password";
+ public static final String JWT_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIiLCJuYW1lIjoiSm9obiBEb2UiLCJpYXQiOjE1MTYyMzkwMjJ9.ih1aovtQShabQ7l0cINw4k1fagApg3qLWiB8Kt59Lno";
+
+ @Mock
+ JwtTokenProvider jwtTokenProvider;
+
+ @Mock
+ UserDetailsService userDetailsService;
+
+ ObjectMapper mapper = new ObjectMapper();
+
+ @InjectMocks
+ TokenAuthenticationInterceptor interceptor;
+
+ @Test
+ void convert() throws IOException {
+ AuthenticationToken token = interceptor.convert(createMockRequest());
+
+ assertThat(token).isEqualTo(new AuthenticationToken(EMAIL, PASSWORD));
+ }
+
+ @Test
+ void authenticate() throws IOException {
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ when(jwtTokenProvider.createToken(any(), any())).thenReturn(JWT_TOKEN);
+
+ interceptor.authenticate(new LoginMember(EMAIL, PASSWORD, List.of()), response);
+
+ assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
+ assertThat(mapper.readValue(response.getContentAsString(), TokenResponse.class)).isEqualTo(new TokenResponse(JWT_TOKEN));
+ }
+
+ @Test
+ void preHandle() throws IOException {
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ given(userDetailsService.loadUserByUsername(any())).willReturn(new LoginMember(EMAIL, PASSWORD, List.of()));
+ given(jwtTokenProvider.createToken(any(), any())).willReturn(JWT_TOKEN);
+ boolean result = interceptor.preHandle(createMockRequest(), response, new Object());
+
+ assertThat(result).isFalse();
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
+ assertThat(response.getContentAsString()).isEqualTo(mapper.writeValueAsString(new TokenResponse(JWT_TOKEN)));
+ }
+
+ private MockHttpServletRequest createMockRequest() throws IOException {
+ MockHttpServletRequest request = new MockHttpServletRequest();
+ TokenRequest tokenRequest = new TokenRequest(EMAIL, PASSWORD);
+ request.setContent(mapper.writeValueAsString(tokenRequest).getBytes());
+
+ return request;
+ }
+} | Java | ์ด๋ฐํํ๋ก ๊ฒ์ฆ๋ ๊ฐ๋ฅํฉ๋๋ค ๐
```suggestion
given(jwtTokenProvider.createToken(any(), any())).willReturn(JWT_TOKEN);
boolean result = interceptor.preHandle(createMockRequest(), response, new Object());
assertThat(result).isFalse();
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(response.getContentAsString()).isEqualTo(mapper.writeValueAsString(new TokenResponse(JWT_TOKEN)));
``` |
@@ -10,7 +10,7 @@
import static org.assertj.core.api.Assertions.assertThat;
class MemberAcceptanceTest extends AcceptanceTest {
- public static final String EMAIL = "email@email.com";
+ public static final String EMAIL = "email2@email.com";
public static final String PASSWORD = "password";
public static final int AGE = 20;
@@ -67,10 +67,32 @@ void deleteMember() {
@DisplayName("ํ์ ์ ๋ณด๋ฅผ ๊ด๋ฆฌํ๋ค.")
@Test
void manageMember() {
+ // given
+ ExtractableResponse<Response> createResponse = ํ์_์์ฑ_์์ฒญ(EMAIL, PASSWORD, AGE);
+ String newEmail = "new@email.com";
+
+ // when
+ ExtractableResponse<Response> response = ํ์_์ ๋ณด_์์ _์์ฒญ(createResponse, newEmail, PASSWORD, AGE);
+ ExtractableResponse<Response> member = ํ์_์ ๋ณด_์กฐํ_์์ฒญ(createResponse);
+
+ // then
+ assertThat(response.statusCode()).isEqualTo(HttpStatus.OK.value());
+ assertThat(member.jsonPath().getString("email")).isEqualTo(newEmail);
}
@DisplayName("๋์ ์ ๋ณด๋ฅผ ๊ด๋ฆฌํ๋ค.")
@Test
void manageMyInfo() {
+ // given
+ ExtractableResponse<Response> createResponse = ํ์_์์ฑ_์์ฒญ(EMAIL, PASSWORD, AGE);
+ String newEmail = "new@email.com";
+
+ // when
+ ExtractableResponse<Response> response = ๋ฒ ์ด์ง_์ธ์ฆ์ผ๋ก_๋ด_ํ์_์ ๋ณด_์์ _์์ฒญ(EMAIL, PASSWORD, newEmail, PASSWORD, AGE);
+ ExtractableResponse<Response> member = ํ์_์ ๋ณด_์กฐํ_์์ฒญ(createResponse);
+
+ // then
+ assertThat(response.statusCode()).isEqualTo(HttpStatus.OK.value());
+ assertThat(member.jsonPath().getString("email")).isEqualTo(newEmail);
}
}
\ No newline at end of file | Java | ์ธ์ํ
์คํธ๋ฅผ ์ฝ๋ ์ฌ๋์ด ๋๊ตฌ์ธ๊ฐ์ ๋ํด ๊ณ ๋ฏผํด๋ด์ผ ํ๋๋ฐ์.
ํด๋ฆฐ ์ ์์ผ์ ๊ตฌ์ ์ ์ธ์ฉํ๋ฉด
>์ธ์ํ
์คํธ๋ ์
๋ฌด ๋ถ์๊ฐ์ QA, ๊ฐ๋ฐ์๊ฐ ํจ๊ป ํ์ ๋ชจ์ ์์ฑํ๋ค.
์ด์ ๊ฐ์ด ์ธ์ํ
์คํธ๋ฅผ ์ฝ๋ ์ฌ๋์ด ๋ชจ๋ ๊ฐ๋ฐ์๋ ์๋ ์ ์๋ค๊ณ ์๊ฐํฉ๋๋ค ๐. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.