code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,87 @@ +import React, { useState } from 'react'; +import { AiFillHeart, AiOutlineComment, AiOutlineUpload } from 'react-icons/ai'; +import { BiDotsHorizontalRounded } from 'react-icons/bi'; +import { GrBookmark } from 'react-icons/gr'; +import './Feeds.scss'; +import Comments from './Comment/Comments'; + +export default function Feeds({ userId, profileImg, img, comments }) { + const [commentVal, setCommentVal] = useState(comments); + let addedCommentVal = [...commentVal]; + const [currInputVal, setCurrInputVal] = useState(''); + + const handleInput = e => { + const { value } = e.target; + if (e.keyCode === 13) uploadComment(); + setCurrInputVal(value); + }; + + const uploadComment = e => { + e.preventDefault(); + if (!currInputVal) return; + addedCommentVal.push({ + id: addedCommentVal.length + 1, + userId: 'userid', + value: currInputVal, + time: '๋ฐฉ๊ธˆ์ „', + }); + setCommentVal(addedCommentVal); + setCurrInputVal(''); + }; + + const handleDelete = e => { + const { id } = e.target.parentNode.parentNode; + addedCommentVal = addedCommentVal.filter(el => el.id !== Number(id)); + setCommentVal(addedCommentVal); + }; + + return ( + <div className="feeds"> + <article> + <div className="top_menu"> + <span> + <img src={profileImg} alt="ํ”„๋กœํ•„" /> + {userId} + </span> + <span> + <BiDotsHorizontalRounded /> + </span> + </div> + <img src={img} alt="๋ฌดํ™”๊ณผ" /> + <div className="bottom_menu"> + <span> + <AiFillHeart className="" /> + </span> + <span> + <AiOutlineComment className="" /> + </span> + <span> + <AiOutlineUpload className="" /> + </span> + <span> + <GrBookmark className="" /> + </span> + </div> + <div className="comments"> + <span>4 Likes</span> + <Comments commentArr={commentVal} handleDelete={handleDelete} /> + </div> + <form className="add_comments"> + <input + type="text" + placeholder="๋Œ“๊ธ€ ๋‹ฌ๊ธฐ..." + className="input_upload" + onChange={handleInput} + value={currInputVal} + /> + <button + className={currInputVal ? 'activated' : ''} + onClick={uploadComment} + > + ๊ฒŒ์‹œ + </button> + </form> + </article> + </div> + ); +}
Unknown
.ํ•ด๋‹น ๋ถ€๋ถ„๋„ ์ข€ ๋” ๋ฐ˜๋ณต๋˜๋Š” ๋‹จ์–ด๋ฅผ ์ค„์ผ ์ˆ˜ ์—†์„์ง€ ๊ณ ๋ฏผํ•ด๋ด…์‹œ๋‹ค. ๋”๋ถˆ์–ด ๋ถˆํ•„์š”ํ•œ state๊ฐ’๋„ ๋ณด์ด๋„ค์š”! ์œ„ ๋ฆฌ๋ทฐ๋ฅผ ์ฐธ๊ณ ํ•ด ์ˆ˜์ •ํ•ด์ฃผ์„ธ์š”!
@@ -0,0 +1,101 @@ +@use '../../../../styles/mixin.scss' as mixin; +@use '../../../../styles/color.scss' as clr; + +.feeds { + position: relative; + top: 77px; + width: 60%; + margin-bottom: 80px; + background: #fff; + + .top_menu { + @include mixin.flex($justify: space-between, $align: center); + height: 82px; + + span { + @include mixin.flex($align: center); + margin-left: 20px; + font-weight: bold; + + &:last-child { + margin-right: 22px; + color: #2a2a2a; + font-size: 35px; + } + + img { + width: 42px; + height: 42px; + border-radius: 50%; + margin-right: 20px; + } + } + } + + article { + img { + width: 100%; + height: 818px; + } + + .bottom_menu { + @include mixin.flex($align: center); + position: relative; + height: 62px; + + span > svg { + margin: 0 10px; + font-size: 32px; + color: #414141; + } + + span:last-child > svg { + position: absolute; + top: 15px; + right: 0; + } + + span:first-child > svg > path { + color: #eb4b59; + } + } + } + + .comments { + display: flex; + flex-direction: column; + + span { + padding-left: 10px; + } + } + + .add_comments { + position: absolute; + @include mixin.flex($justify: space-between, $align: center); + bottom: -62px; + width: 100%; + height: 62px; + border-top: 1px solid clr.$clr-border; + font-size: 14px; + + input { + width: 90%; + height: 50%; + margin-left: 15px; + border: none; + } + + button { + margin-right: 15px; + border: none; + color: clr.$clr-primary; + opacity: 0.5; + background: #fff; + + &.activated { + opacity: 1; + } + } + } +}
Unknown
class๋ช…์€ ์–ด๋–ค ํ˜•ํƒœ๊ฐ€ ์ข‹์„๊นŒ์š”?! ํ•ด๋‹น class๋ช…์€ '๋™์ž‘'์„ ๋‚˜ํƒ€๋‚ด๊ธฐ์— ํด๋ž˜์Šค ๋„ค์ž„๋ณด๋‹ค๋Š” ํ•จ์ˆ˜๋ช…์ฒ˜๋Ÿผ ๋А๊ปด์ง‘๋‹ˆ๋‹ค!
@@ -1,5 +1,98 @@ import React from 'react'; +import { useState, useEffect } from 'react'; +import { useNavigate } from 'react-router-dom'; +import './Login.scss'; -export default function Login() { - return <div>Hello, Hyeonze!</div>; -} +const Login = () => { + const [idInput, setIdInput] = useState(''); + const [pwInput, setPwInput] = useState(''); + const [isValidatedUser, setIsValidatedUser] = useState(false); + + const navigate = useNavigate(); + const changeIdInput = e => { + const { value } = e.target; + setIdInput(value); + }; + + const changePwInput = e => { + const { value } = e.target; + setPwInput(value); + }; + + useEffect(() => { + setIsValidatedUser(idInput.indexOf('@') !== -1 && pwInput.length > 4); + }, [idInput, pwInput]); + + // ๋ฉ”์ธ์œผ๋กœ ์ด๋™ํ•  ๋•Œ ๋กœ์ง + const goToMain = () => { + navigate('/main-hyeonze'); + }; + + // ํšŒ์›๊ฐ€์ž…์‹œ ์‚ฌ์šฉํ•  ๋กœ์ง + // const signup = () => { + // fetch('http://10.58.4.22:8000/users/signup', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('๊ฒฐ๊ณผ: ', result.message) + // if (result.message === 'EMAIL_ALREADY_EXISTS') { + // console.log('Error : Duplicated'); + // } + // }); + // }; + + // ๋กœ๊ทธ์ธ์‹œ ์‚ฌ์šฉํ•  ๋กœ์ง + // const login = () => { + // fetch('http://10.58.4.22:8000/users/login', { + // method: 'POST', + // body: JSON.stringify({ + // email: idInput, + // password: pwInput, + // }), + // }) + // .then(response => response.json()) + // .then(result => { + // //console.log('๊ฒฐ๊ณผ: ', result.message) + // if (result.message === 'SUCCESS') { + // console.log('login SUCCESS'); + // } + // }); + // }; + + return ( + <div className="login"> + <div id="wrapper"> + <h1>westagram</h1> + <form className="login_form"> + <input + type="text" + placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" + className="username" + onChange={changeIdInput} + /> + <input + type="password" + placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" + className="userpassword" + onChange={changePwInput} + /> + <input + className={isValidatedUser ? 'activated' : ''} + disabled={!isValidatedUser} + type="button" + value="๋กœ๊ทธ์ธ" + onClick={goToMain} + /> + </form> + <p>๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”?</p> + </div> + </div> + ); +}; + +export default Login;
Unknown
- ๋ถˆํ•„์š”ํ•œ ์ฃผ์„์ฒ˜๋ฆฌ๋Š” ์‚ญ์ œํ•ด์ฃผ์„ธ์š”! - ๋”๋ถˆ์–ด์„œ className ์ž์ฒด๋ฅผ '์ƒ‰'์œผ๋กœ ์ง€์ •ํ•˜๋Š” ๊ฒƒ์€ ์ข‹์€ ๋„ค์ด๋ฐ์€ ์•„๋‹Œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์–ด๋–ค ๋„ค์ด๋ฐ์ด ์ ํ•ฉํ• ์ง€ ๊ณ ๋ฏผํ•˜์…”์„œ , ํ•ด๋‹น ์š”์†Œ๊ฐ€ ๋ฌด์—‡์ธ์ง€๋ฅผ ์ž˜ ๋‚˜ํƒ€๋‚ด๋Š” ๋„ค์ด๋ฐ์œผ๋กœ ์ˆ˜์ •ํ•ด์ฃผ์„ธ์š”. - ํ”Œ๋Ÿฌ์Šค! ์—ฌ๊ธฐ์—๋„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์•„๋„ ๋˜๋Š” ์‚ผํ•ญ์—ฐ์‚ฌ์ž๊ฐ€ ์ˆจ์–ด์žˆ๋„ค์š”! ํ™•์ธํ•ด์ฃผ์„ธ์š”
@@ -0,0 +1,101 @@ +@use '../../../../styles/mixin.scss' as mixin; +@use '../../../../styles/color.scss' as clr; + +.feeds { + position: relative; + top: 77px; + width: 60%; + margin-bottom: 80px; + background: #fff; + + .top_menu { + @include mixin.flex($justify: space-between, $align: center); + height: 82px; + + span { + @include mixin.flex($align: center); + margin-left: 20px; + font-weight: bold; + + &:last-child { + margin-right: 22px; + color: #2a2a2a; + font-size: 35px; + } + + img { + width: 42px; + height: 42px; + border-radius: 50%; + margin-right: 20px; + } + } + } + + article { + img { + width: 100%; + height: 818px; + } + + .bottom_menu { + @include mixin.flex($align: center); + position: relative; + height: 62px; + + span > svg { + margin: 0 10px; + font-size: 32px; + color: #414141; + } + + span:last-child > svg { + position: absolute; + top: 15px; + right: 0; + } + + span:first-child > svg > path { + color: #eb4b59; + } + } + } + + .comments { + display: flex; + flex-direction: column; + + span { + padding-left: 10px; + } + } + + .add_comments { + position: absolute; + @include mixin.flex($justify: space-between, $align: center); + bottom: -62px; + width: 100%; + height: 62px; + border-top: 1px solid clr.$clr-border; + font-size: 14px; + + input { + width: 90%; + height: 50%; + margin-left: 15px; + border: none; + } + + button { + margin-right: 15px; + border: none; + color: clr.$clr-primary; + opacity: 0.5; + background: #fff; + + &.activated { + opacity: 1; + } + } + } +}
Unknown
์ด๋ ‡๊ฒŒ ๊ฐ ์š”์†Œ์— background color๋ฅผ ๊ฐ๊ฐ ๋‹ค ๋„ฃ์–ด์ฃผ์‹  ์ด์œ ๊ฐ€ ์žˆ์œผ์‹ค๊นŒ์š”?
@@ -0,0 +1,92 @@ +{ + "stories": [ + { "imgUrl": "images/joonyoung/stories/story1.jpg", "username": "Enna" }, + { "imgUrl": "images/joonyoung/stories/story2.jpg", "username": "Jesy" }, + { "imgUrl": "images/joonyoung/stories/story3.jpg", "username": "Denial" }, + { "imgUrl": "images/joonyoung/stories/story4.jpg", "username": "Meow" }, + { + "imgUrl": "images/joonyoung/stories/story5.jpg", + "username": "Christina" + }, + { "imgUrl": "images/joonyoung/stories/story6.jpg", "username": "Mally" }, + { "imgUrl": "images/joonyoung/stories/story7.jpg", "username": "Karel" }, + { "imgUrl": "images/joonyoung/stories/story8.jpg", "username": "Bred" }, + { "imgUrl": "images/joonyoung/stories/story9.jpg", "username": "Andrew" }, + { "imgUrl": "images/joonyoung/stories/story10.jpg", "username": "Emily" } + ], + "otherProfileInfos": [ + { + "id": 1, + "username": "wecode28๊ธฐ", + "description": "wecode๋‹˜์™ธ 36๋ช…์ด follow" + }, + { + "id": 2, + "username": "Younha", + "description": "Enna Kim์™ธ 10๋ช…์ด follow" + }, + { + "id": 3, + "username": "wework", + "description": "wecode28๋‹˜์™ธ 236๋ช…์ด follow" + } + ], + "feed": [ + { + "id": 1, + "feedUpLoader": "Enna", + "uploaderProfileImg": "./images/joonyoung/stories/story1.jpg", + "uploaderInfo": "Enna's Feed icon", + "carouselImages": [ + "./images/joonyoung/feed/feed1/pexels-fauxels-3184291.jpg", + "./images/joonyoung/feed/feed1/pexels-fauxels-3184302.jpg", + "./images/joonyoung/feed/feed1/pexels-fauxels-3184433.jpg", + "./images/joonyoung/feed/feed1/pexels-min-an-853168.jpg", + "./images/joonyoung/feed/feed1/pexels-this-is-zun-1116302.jpg" + ], + "likes": 1129, + "comments": [ + { + "id": 1, + "user": "28๊ธฐ ์–‘๋Œ€์˜๋‹˜", + "comment": "์—ฌ๋Ÿฌ๋ถ„ ์น˜ํ‚จ๊ณ„ ์“ฐ์…”์•ผ ํ•ฉ๋‹ˆ๋‹ค..!!ย ๐Ÿ‘€ ๐Ÿ‘€" + }, + { + "id": 2, + "user": "28๊ธฐ ์ด์•„์˜๋‹˜", + "comment": "๋Œ€์˜๋‹˜๋„ ์•ˆ ์“ฐ์…จ์ž–์•„์š”?! ๐Ÿคญ" + }, + { + "id": 3, + "user": "28๊ธฐ ๋ฐ•์œค๊ตญ๋‹˜", + "comment": "๐ŸŽธ ๐ŸŽธ ๐ŸŽธ (์‹ ๊ณก ํ™๋ณด์ค‘)" + } + ] + }, + { + "id": 2, + "feedUpLoader": "James", + "uploaderProfileImg": "./images/joonyoung/stories/story2.jpg", + "uploaderInfo": "It's jesy!", + "carouselImages": [ + "./images/joonyoung/feed/feed2/handtohand.jpg", + "./images/joonyoung/feed/feed2/branch.jpg", + "./images/joonyoung/feed/feed2/pexels-te-lensfix-1371360.jpg", + "./images/joonyoung/feed/feed2/pexels-victor-freitas-803105.jpg" + ], + "likes": 1129, + "comments": [ + { + "id": 1, + "user": "๋ฉ˜ํ†  ๊น€INTP๋‹˜", + "comment": "(์•ˆ๊ฒฝ์„ ์น˜์ผœ ์˜ฌ๋ฆฌ๋ฉฐ) git branch merge" + }, + { + "id": 2, + "user": "28๊ธฐ ์ดESTJ๋‹˜", + "comment": "์•„๋‹ˆ ๊ณ„ํš์„ ์•ˆ์งœ๊ณ  ์—ฌํ–‰์„ ๊ฐ„๋‹ค๊ณ ?" + } + ] + } + ] +}
Unknown
mockData king ์ค€์˜๋‹˜๐Ÿ‘ ์ •๋ง ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ์„ธ๋ถ€ ๋‚ด์šฉ์€ ์ž„์˜๋กœ ๋ณ€๊ฒฝํ•œ ํ›„, ๋ฐ์ดํ„ฐ์˜ ํ˜•์‹์ข€ ๋นŒ๋ ค๋‹ค ์“ฐ๊ฒ ์Šต๋‹ˆ๋‹ค ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,12 @@ +.header { + display: flex; + justify-content: space-between; + align-items: center; + position: fixed; + width: calc(430px - 48px); + height: 64px; + padding: 0 24px; + background-color: black; + color: #fff; + z-index: 1000; +}
Unknown
ํ”ผ๊ทธ๋งˆ ์‹œ์•ˆ width๊ฐ€ 430px์ด์—ˆ๊ณ , ์–‘ ์˜† padding์ด 24์˜€์–ด์„œ ์ด๋Ÿฐ calc ์ฝ”๋“œ๊ฐ€ ๋‚˜์™”์Šต๋‹ˆ๋‹ค.. โœ‹๐Ÿป๋ณดํ†ต ์ด๋ ‡๊ฒŒ ์ฒ˜๋ฆฌํ•˜์‹œ๋Š”์ง€, ํ˜น์€ ๋” ์œ ์—ฐํ•œ ๋ฐฉ์‹์ด ์žˆ๋Š”์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค.
@@ -4,13 +4,15 @@ "version": "0.0.0", "type": "module", "scripts": { - "dev": "vite", + "dev": "vite --host", "build": "tsc && vite build", "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", "preview": "vite preview", "test": "vitest" }, "dependencies": { + "@jaymyong66/simple-modal": "^0.0.7", + "@tanstack/react-query": "^5.40.1", "react": "^18.2.0", "react-dom": "^18.2.0" },
Unknown
๊ต‰์žฅํžˆ ์‚ฌ์†Œํ•˜์ง€๋งŒ ์ปค๋ฐ‹ ๋ฉ”์‹œ์ง€ ๊ด€๋ จ ๋ฆฌ๋ทฐ ๋‚จ๊ฒจ๋ด…๋‹ˆ๋‹ค..! ์ €๋Š” ํŒจํ‚ค์ง€ ๊ด€๋ จ ์„ค์น˜๋Š” chore๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค..! ์ด๊ฒŒ ์™„๋ฒฝํ•˜๊ฒŒ ์ •ํ™•ํ•œ ์ง€๋Š” ๊ฒ€์ฆํ•ด๋ณด์ง€ ์•Š์•˜์œผ๋‚˜, ์ฐธ๊ณ ํ•ด๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! [์ข‹์€ ์ปค๋ฐ‹ ๋ฉ”์‹œ์ง€ ์ž‘์„ฑ๋ฒ•](https://velog.io/@iamjm29/Git-%EC%A2%8B%EC%9D%80-%EC%BB%A4%EB%B0%8B-%EB%A9%94%EC%8B%9C%EC%A7%80-%EC%9E%91%EC%84%B1%EB%B2%95) [AngularJS Commit Convention](https://gist.github.com/stephenparish/9941e89d80e2bc58a153)
@@ -0,0 +1,12 @@ +.header { + display: flex; + justify-content: space-between; + align-items: center; + position: fixed; + width: calc(430px - 48px); + height: 64px; + padding: 0 24px; + background-color: black; + color: #fff; + z-index: 1000; +}
Unknown
๋Œ€๋ฐ• ์™œ ์ด์ œ ์•Œ์•˜์ง€..? ๐Ÿ‘
@@ -0,0 +1,18 @@ +package racingcar.view; + +import camp.nextstep.edu.missionutils.Console; + +public class InputView { + private static final String ASK_CAR_NAMES = "๊ฒฝ์ฃผํ•  ์ž๋™์ฐจ ์ด๋ฆ„์„ ์ž…๋ ฅํ•˜์„ธ์š”.(์ด๋ฆ„์€ ์‰ผํ‘œ(,) ๊ธฐ์ค€์œผ๋กœ ๊ตฌ๋ถ„)"; + private static final String ASK_TURN = "์‹œ๋„ํ•  ํšŒ์ˆ˜๋Š” ๋ช‡ํšŒ์ธ๊ฐ€์š”?"; + + public static String readCarNames() { + System.out.println(ASK_CAR_NAMES); + return Console.readLine(); + } + + public static String readTurn() { + System.out.println(ASK_TURN); + return Console.readLine(); + } +}
Java
๋ฉ”์‹œ์ง€ ๊ด€๋ฆฌ์— ๋Œ€ํ•ด์„œ static์ด ์ข‹์€์ง€ enum์ด ์ข‹์€์ง€ ์ด์•ผ๊ธฐ ๋‚˜๋ˆ ๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ํ•ญ์ƒ ์–ด๋–ค๊ฒŒ ๋‚˜์€์ง€ ๊ณ ๋ฏผํ•ด์„œ ๋งค๋ฒˆ ์“ธ๋•Œ๋งˆ๋‹ค ํ•œ๋ฒˆ์€ ์ด๋ ‡๊ฒŒ ํ•œ๋ฒˆ์€ ์ €๋ ‡๊ฒŒ ํ–ˆ์—ˆ๊ฑฐ๋“ ์š”.
@@ -0,0 +1,18 @@ +package racingcar.view; + +import camp.nextstep.edu.missionutils.Console; + +public class InputView { + private static final String ASK_CAR_NAMES = "๊ฒฝ์ฃผํ•  ์ž๋™์ฐจ ์ด๋ฆ„์„ ์ž…๋ ฅํ•˜์„ธ์š”.(์ด๋ฆ„์€ ์‰ผํ‘œ(,) ๊ธฐ์ค€์œผ๋กœ ๊ตฌ๋ถ„)"; + private static final String ASK_TURN = "์‹œ๋„ํ•  ํšŒ์ˆ˜๋Š” ๋ช‡ํšŒ์ธ๊ฐ€์š”?"; + + public static String readCarNames() { + System.out.println(ASK_CAR_NAMES); + return Console.readLine(); + } + + public static String readTurn() { + System.out.println(ASK_TURN); + return Console.readLine(); + } +}
Java
์ €๋Š” System.out.print~์‚ฌ์šฉํ•˜๋Š” ๋ถ€๋ถ„์€ ์ „๋ถ€ ์ถœ๋ ฅ์œผ๋กœ ์‚ฌ์šฉ์ž์—๊ฒŒ ๋ณด์—ฌ์ง€๋Š” ๋ถ€๋ถ„์ด๋ผ๊ณ  ์ƒ๊ฐํ•ด์„œ ๋ชจ๋‘ OutputView์— ์ž‘์„ฑํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์‚ฌ์‹ค ์ฒจ์— ์ €๋„ InputView์— ์จ๋„ ๋ ์ง€ ๊ณ ๋ฏผํ–ˆ๋Š”๋ฐ ์ด ๋ถ€๋ถ„์— ๋Œ€ํ•ด์„œ๋Š” ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋Š”์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,38 @@ +package racingcar.view; + +import java.util.stream.Collectors; +import racingcar.domain.RacingCar; +import racingcar.domain.RacingCars; +import racingcar.domain.Winner; + +public class OutputView { + private static final String RACE_RESULT_MESSAGE = "\n์‹คํ–‰ ๊ฒฐ๊ณผ"; + private static final String DISTANCE_UNIT = "-"; + private static final String RACE_RESULT_FORMAT = "%s : %s%n"; + private static final String WINNER = "์ตœ์ข… ์šฐ์Šน์ž : "; + private static final String DELIMITER = ", "; + + public static void printRaceResultNotice() { + System.out.println(RACE_RESULT_MESSAGE); + } + + public static void printRaceResult(RacingCars racingCars) { + racingCars.getRacingCars() + .forEach(racingCar -> System.out.printf(RACE_RESULT_FORMAT + , racingCar.getCarName(), changeDistanceForm(racingCar.getDistance()))); + System.out.println(); + } + + private static String changeDistanceForm(int distance) { + return DISTANCE_UNIT.repeat(distance); + } + + public static void printWinner(Winner winner) { + System.out.print(WINNER); + String winners = winner.getWinner() + .stream() + .map(RacingCar::getCarName) + .collect(Collectors.joining(DELIMITER)); + System.out.println(winners); + } +}
Java
Winnerํด๋ž˜์Šค์˜ getWinner()์—์„œ ์•„๋ž˜ ์—ฐ์‚ฐ์ด ๋๋‚œ ๊ฒฐ๊ณผ๋ฅผ ๋ฆฌํ„ดํ•˜๋ฉด getter๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ ๋„ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ›์•„์˜ฌ ์ˆ˜ ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ•˜๋Š”๋ฐ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -0,0 +1,17 @@ +package racingcar.domain; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class CarNameTest { + @ParameterizedTest + @DisplayName("์ฐจ๋Ÿ‰์ด๋ฆ„์€ 1-5๊ธ€์ž์ด๊ณ  ํŠน์ˆ˜๋ฌธ์ž๋ฅผ ํฌํ•จํ•˜์ง€ ์•Š๋Š”๋‹ค.") + @ValueSource(strings = {"abcdef", "", "$", "&", " ", "!", "(", "$", "%"}) + void createCarName(String input) { + assertThatThrownBy(() -> new CarName(input)) + .isInstanceOf(IllegalArgumentException.class); + } +} \ No newline at end of file
Java
assertThatCode๋ฅผ ์ด์šฉํ•ด์„œ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•˜์ง€ ์•Š๊ณ  ์˜ฌ๋ฐ”๋ฅด๊ฒŒ ๋˜๋Š”์ง€ ํ•œ๋ฒˆ ํ…Œ์ŠคํŠธ ํ•ด๋ณด๋Š” ๊ฒƒ๋„ ์ถ”์ฒœ ๋“œ๋ฆฝ๋‹ˆ๋‹ค.
@@ -0,0 +1,22 @@ +package racingcar.domain; + +public enum ErrorMessage { + ERROR("[ERROR] "), + INVALID_NAME_LENGTH(ERROR + "์ฐจ๋Ÿ‰ ์ด๋ฆ„์€ 1-5๊ธ€์ž ์‚ฌ์ด์—ฌ์•ผ ํ•ฉ๋‹ˆ๋‹ค."), + INVALID_NAME_TYPE(ERROR + "์ฐจ๋Ÿ‰ ์ด๋ฆ„์€ ํŠน์ˆ˜๋ฌธ์ž๋ฅผ ํฌํ•จํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + DUPLICATED_NAME(ERROR + "์ฐจ๋Ÿ‰ ์ด๋ฆ„์€ ์ค‘๋ณต๋  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + INVALID_RACING_CARS_SIZE(ERROR + "๊ฒฝ์ฃผ์—๋Š” ์ตœ์†Œ 2๋Œ€์˜ ์ฐจ๋Ÿ‰์ด ์ฐธ์—ฌํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค."), + INVALID_TURN_RANGE(ERROR + "์‹œ๋„ํšŸ์ˆ˜๋Š” ์ตœ์†Œ 1ํšŒ ์ด์ƒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค."), + INVALID_TURN_TYPE(ERROR + "์ˆซ์ž ์ด์™ธ์˜ ๊ฐ’์€ ์ž…๋ ฅํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + CANT_FIND_CAR(ERROR + "์ฐจ๋Ÿ‰์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + + private final String message; + + ErrorMessage(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } +}
Java
ERROR์€ ๋ณ€ํ•จ ์—†์„ ๊ฒƒ ๊ฐ™์€๋ฐ ์ƒ์ˆ˜๋กœ ๋‘๊ณ  ์ƒ์„ฑ์ž ๋ถ€๋ถ„์—์„œ this.message = "ERROR" + message๋กœ ํ•œ๋‹ค๋ฉด ๋ฉ”์‹œ์ง€ ์ž‘์„ฑํ•  ๋•Œ ์ค‘๋ณต์„ ํ”ผํ•˜๋Š”๋ฐ ๋„์›€ ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,63 @@ +package racingcar.domain; + +import static racingcar.domain.ErrorMessage.CANT_FIND_CAR; +import static racingcar.domain.ErrorMessage.DUPLICATED_NAME; +import static racingcar.domain.ErrorMessage.INVALID_RACING_CARS_SIZE; + +import java.util.List; +import java.util.stream.Collectors; + +public class RacingCars { + private static final int MIN_SIZE = 2; + private final List<RacingCar> racingCars; + private RacingCar maxDistanceCar; + + public RacingCars(List<RacingCar> racingCars) { + validateSize(racingCars); + validateDuplicated(racingCars); + this.racingCars = racingCars; + } + + private void validateSize(List<RacingCar> racingCars) { + if (racingCars.size() < MIN_SIZE) { + throw new IllegalArgumentException(INVALID_RACING_CARS_SIZE.getMessage()); + } + } + + private void validateDuplicated(List<RacingCar> racingCars) { + if (isDuplicated(racingCars)) { + throw new IllegalArgumentException(DUPLICATED_NAME.getMessage()); + } + } + + private boolean isDuplicated(List<RacingCar> racingCars) { + int sizeAfterCut = (int) racingCars.stream() + .distinct() + .count(); + return racingCars.size() != sizeAfterCut; + } + + public void startRace() { + racingCars + .forEach(racingCar -> + racingCar.moveForward(RandomNumberGenerator.generateRandomNumber())); + } + + public Winner selectWinner() { + findMaxDistanceCar(); + List<RacingCar> winner = racingCars.stream() + .filter(maxDistanceCar::isWinner) + .collect(Collectors.toList()); + return new Winner(winner); + } + + private void findMaxDistanceCar() { + maxDistanceCar = racingCars.stream() + .max(RacingCar::compareTo) + .orElseThrow(() -> new IllegalArgumentException(CANT_FIND_CAR.getMessage())); + } + + public List<RacingCar> getRacingCars() { + return racingCars; + } +}
Java
return์— ๋ฐ”๋กœ ์ž‘์„ฑํ•˜๋ฉด ๊ฐ€๋…์„ฑ์ด ์กฐ๊ธˆ ๋–จ์–ด์ ธ ๋ณด์ผ๊นŒ์š”? ์ด ๋ฉ”์†Œ๋“œ ์ฒ˜๋Ÿผ ํ•œ๋ฒˆ๋งŒ ์‚ฌ์šฉํ•˜๋Š” ๋ณ€์ˆ˜๋ผ๋ฉด ๋ณ€์ˆ˜๋กœ ์ง€์ •ํ•˜์ง€ ์•Š๊ณ  ๋ฐ”๋กœ ์ž‘์„ฑํ•ด๋„ ๋  ๊ฒƒ ๊ฐ™์€๋ฐ... ์ด๋Ÿฌ๋ฉด ๊ฐ€๋…์„ฑ์ด ๋–จ์–ด์ ธ ๋ณด์ด๊ธฐ๋„ ํ•  ๊ฒƒ ๊ฐ™์•„ ๊ณ ๋ฏผ์ด ๋˜์„œ ์—ฌ์ญค๋ด…๋‹ˆ๋‹ค.
@@ -0,0 +1,51 @@ +package racingcar.domain; + +import static racingcar.domain.ErrorMessage.INVALID_NAME_LENGTH; +import static racingcar.domain.ErrorMessage.INVALID_NAME_TYPE; + +import java.util.Objects; +import java.util.regex.Pattern; + +public class CarName { + private static final int MAX_LENGTH = 5; + private static final String REGEX = "[0-9|a-zA-Zใ„ฑ-ใ…Žใ…-ใ…ฃ๊ฐ€-ํžฃ]*"; + private final String carName; + + public CarName(String carName) { + validateLength(carName); + validateType(carName); + this.carName = carName; + } + + private void validateLength(String carName) { + if (carName.isEmpty() || carName.length() > MAX_LENGTH) { + throw new IllegalArgumentException(INVALID_NAME_LENGTH.getMessage()); + } + } + + private void validateType(String carName) { + if (!Pattern.matches(REGEX, carName)) { + throw new IllegalArgumentException(INVALID_NAME_TYPE.getMessage()); + } + } + + public String getCarName() { + return carName; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof CarName carName1)) { + return false; + } + return Objects.equals(carName, carName1.carName); + } + + @Override + public int hashCode() { + return Objects.hash(carName); + } +}
Java
์ •๊ทœํ‘œํ˜„์‹์— ๋ฌธ์ž์ง€์ •ํ•œ ํ›„ {1,5}์„ ์‚ฌ์šฉํ•˜๋ฉด ๊ธ€์ž ์ˆ˜ ์ œํ•œ ํ•˜๋Š”๋ฐ๋„ ๋„์›€์ด ๋  ๊ฑฐ์—์š”.
@@ -0,0 +1,35 @@ +package racingcar.domain; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class RacingCarsTest { + @ParameterizedTest + @DisplayName("๊ฒฝ์ฃผ์—๋Š” ์ตœ์†Œ 2๋Œ€ ์ด์ƒ์˜ ์ฐจ๋Ÿ‰์ด ์ฐธ์—ฌํ•ด์•ผ ํ•˜๋ฉฐ ์ค‘๋ณต๋  ์ˆ˜ ์—†๋‹ค.") + @ValueSource(strings = {"์ƒ์ถ”", "์ƒ์ถ”,์ƒ์ถ”"}) + void createRacingCars(String input) { + List<RacingCar> racingCars = InputConvertor.convertToRacingCars(input); + assertThatThrownBy(() -> new RacingCars(racingCars)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("์šฐ์Šน์ž๋Š” ์ƒ์ถ”์™€ ๋ฐฐ์ถ”๋‹ค.") + void selectWinner() { + RacingCar sangchu = new RacingCar(new CarName("์ƒ์ถ”")); + RacingCar baechu = new RacingCar(new CarName("๋ฐฐ์ถ”")); + RacingCar moodosa = new RacingCar(new CarName("๋ฌด๋„์‚ฌ")); + RacingCars racingCars = new RacingCars(List.of(sangchu, baechu, moodosa)); + sangchu.moveForward(5); + baechu.moveForward(6); + Winner winner = racingCars.selectWinner(); + assertThat(winner.getWinner().get(0).getCarName()).isEqualTo("์ƒ์ถ”"); + assertThat(winner.getWinner().get(1).getCarName()).isEqualTo("๋ฐฐ์ถ”"); + } +} \ No newline at end of file
Java
2๋Œ€ ์ด์ƒ์ธ ๊ฒฝ์šฐ / ์ด๋ฆ„ ์ค‘๋ณต๋˜๋ฉด ์•ˆ๋˜๋Š” ๊ฒฝ์šฐ์— ๋Œ€ํ•ด ๋ฉ”์†Œ๋“œ๋ฅผ ๋‚˜๋ˆ ์„œ ํ…Œ์ŠคํŠธ ํ•ด๋„ ์ข‹์„๊ฑฐ๊ฐ™์Šด๋‹ค
@@ -0,0 +1,17 @@ +package racingcar.domain; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class TurnTest { + @ParameterizedTest + @DisplayName("1ํšŒ ๋ฏธ๋งŒ, ์ˆซ์ž ์ด์™ธ ๊ฐ’ ์ž…๋ ฅ์‹œ ์˜ˆ์™ธ ๋ฐœ์ƒ") + @ValueSource(strings = {"0", "-1", "d", "#", "", " "}) + void createTurn(String input) { + assertThatThrownBy(() -> new Turn(input)) + .isInstanceOf(IllegalArgumentException.class); + } +} \ No newline at end of file
Java
์ €๋Š” validate ๋กœ์ง์— ๋Œ€ํ•ด์„œ 1. ์ˆซ์ž๋งŒ ์ž…๋ ฅ ๋ฐ›์•„์•ผํ•˜๋Š” ๋ณ€์ˆ˜์— ๋ฌธ์ž ์ž…๋ ฅ๋˜๋Š” ๊ฒฝ์šฐ -> input์—์„œ ๊ฒ€์ฆ 2. 1ํšŒ ๋ฏธ๋งŒ์œผ๋กœ ์ž…๋ ฅ๋ฐ›๋Š” ๋ฉ”์†Œ๋“œ ๊ด€๋ จ ๊ฒ€์ฆ -> turn๋ฉ”์†Œ๋“œ์—์„œ ๊ฒ€์ฆ ํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ํ•ญ์ƒ ์ž‘์„ฑํ•ด ์™”๋Š”๋ฐ ์ด๋ถ€๋ถ„์— ๋Œ€ํ•ด์„œ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜๋Š”์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค !
@@ -0,0 +1,18 @@ +package racingcar.view; + +import camp.nextstep.edu.missionutils.Console; + +public class InputView { + private static final String ASK_CAR_NAMES = "๊ฒฝ์ฃผํ•  ์ž๋™์ฐจ ์ด๋ฆ„์„ ์ž…๋ ฅํ•˜์„ธ์š”.(์ด๋ฆ„์€ ์‰ผํ‘œ(,) ๊ธฐ์ค€์œผ๋กœ ๊ตฌ๋ถ„)"; + private static final String ASK_TURN = "์‹œ๋„ํ•  ํšŒ์ˆ˜๋Š” ๋ช‡ํšŒ์ธ๊ฐ€์š”?"; + + public static String readCarNames() { + System.out.println(ASK_CAR_NAMES); + return Console.readLine(); + } + + public static String readTurn() { + System.out.println(ASK_TURN); + return Console.readLine(); + } +}
Java
์ €๋Š” ์ด๋ฒˆ์— ํ”„๋ฆฌ์ฝ”์Šค๋ฅผ ์ง„ํ–‰ํ•˜๋ฉด์„œ ๋‚˜๋ฆ„์˜ ๊ธฐ์ค€์„ ์„ธ์›Œ๋ดค์Šต๋‹ˆ๋‹ค! 1. enum์œผ๋กœ ์‚ฌ์šฉํ• ๋งŒํผ ์ƒ์ˆ˜์˜ ๊ฐœ์ˆ˜๊ฐ€ ์ถฉ๋ถ„ํ•œ์ง€? ์ตœ์†Œ 3๊ฐœ ์ด์ƒ 2. ํ”„๋กœ๊ทธ๋žจ์ด ํ™•์žฅ๋œ๋‹ค๋ฉด ํ•ด๋‹น enum ์— ์ƒ์ˆ˜๊ฐ€ ์ถ”๊ฐ€๋  ๊ฐ€๋Šฅ์„ฑ์ด ์žˆ๋Š”์ง€? 3. ๋‹ค๋ฅธ ํด๋ž˜์Šค์—์„œ๋„ ์‚ฌ์šฉ๋  ๊ฐ€๋Šฅ์„ฑ์ด ์žˆ๋Š”์ง€?
@@ -0,0 +1,18 @@ +package racingcar.view; + +import camp.nextstep.edu.missionutils.Console; + +public class InputView { + private static final String ASK_CAR_NAMES = "๊ฒฝ์ฃผํ•  ์ž๋™์ฐจ ์ด๋ฆ„์„ ์ž…๋ ฅํ•˜์„ธ์š”.(์ด๋ฆ„์€ ์‰ผํ‘œ(,) ๊ธฐ์ค€์œผ๋กœ ๊ตฌ๋ถ„)"; + private static final String ASK_TURN = "์‹œ๋„ํ•  ํšŒ์ˆ˜๋Š” ๋ช‡ํšŒ์ธ๊ฐ€์š”?"; + + public static String readCarNames() { + System.out.println(ASK_CAR_NAMES); + return Console.readLine(); + } + + public static String readTurn() { + System.out.println(ASK_TURN); + return Console.readLine(); + } +}
Java
์ €๋„ ์ฒ˜์Œ์— 1์ฃผ์ฐจ ๋ฏธ์…˜์„ ์ง„ํ–‰ํ•  ๋•Œ๋Š” ์‚ฌ์šฉ์ž์—๊ฒŒ ๋ณด์ด๋Š” ๋ถ€๋ถ„์ด๋ผ๊ณ  ์ƒ๊ฐํ•˜์—ฌ OutputView์— ์ž‘์„ฑํ–ˆ์—ˆ๋Š”๋ฐ ๋งŽ์€ ๋ถ„๋“ค ์ฝ”๋“œ๋ฅผ ๋ณด๋‹ค๋ณด๋‹ˆ ์ž…๋ ฅ์„ ์š”์ฒญํ•˜๋Š” ๋ฉ”์‹œ์ง€๋Š” InputView์—์„œ ์ฒ˜๋ฆฌํ•˜์‹œ๋”๋ผ๊ตฌ์š”. ๊ทธ๋ฆฌ๊ณ  ๊ฒฐ์ •์ ์œผ๋กœ ์šฐํ…Œ์ฝ”์—์„œ ์ œ๊ณตํ•œ ์š”๊ตฌ์‚ฌํ•ญ ๋ถ€๋ถ„์„ ๋ณด์‹œ๋ฉด ์ž…๋ ฅ์„ ์š”๊ตฌํ•˜๋Š” ๋ฉ”์‹œ์ง€๋ฅผ InputView์—์„œ ์‚ฌ์šฉํ•˜๋Š”๊ฑธ ๋ณด์‹ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. <img width="914" alt="image" src="https://github.com/parksangchu/java-racingcar-6/assets/142131857/87aa54ff-07c6-4c03-87fe-331d6aba9664">
@@ -0,0 +1,22 @@ +package racingcar.domain; + +public enum ErrorMessage { + ERROR("[ERROR] "), + INVALID_NAME_LENGTH(ERROR + "์ฐจ๋Ÿ‰ ์ด๋ฆ„์€ 1-5๊ธ€์ž ์‚ฌ์ด์—ฌ์•ผ ํ•ฉ๋‹ˆ๋‹ค."), + INVALID_NAME_TYPE(ERROR + "์ฐจ๋Ÿ‰ ์ด๋ฆ„์€ ํŠน์ˆ˜๋ฌธ์ž๋ฅผ ํฌํ•จํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + DUPLICATED_NAME(ERROR + "์ฐจ๋Ÿ‰ ์ด๋ฆ„์€ ์ค‘๋ณต๋  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + INVALID_RACING_CARS_SIZE(ERROR + "๊ฒฝ์ฃผ์—๋Š” ์ตœ์†Œ 2๋Œ€์˜ ์ฐจ๋Ÿ‰์ด ์ฐธ์—ฌํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค."), + INVALID_TURN_RANGE(ERROR + "์‹œ๋„ํšŸ์ˆ˜๋Š” ์ตœ์†Œ 1ํšŒ ์ด์ƒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค."), + INVALID_TURN_TYPE(ERROR + "์ˆซ์ž ์ด์™ธ์˜ ๊ฐ’์€ ์ž…๋ ฅํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + CANT_FIND_CAR(ERROR + "์ฐจ๋Ÿ‰์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + + private final String message; + + ErrorMessage(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } +}
Java
enum ์ƒ์„ฑ์ž์— ๋Œ€ํ•œ ์ดํ•ด๊ฐ€ ๋ถ€์กฑํ–ˆ๋˜๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ! ์ข‹์€ ์กฐ์–ธ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ใ…Žใ…Ž
@@ -0,0 +1,63 @@ +package racingcar.domain; + +import static racingcar.domain.ErrorMessage.CANT_FIND_CAR; +import static racingcar.domain.ErrorMessage.DUPLICATED_NAME; +import static racingcar.domain.ErrorMessage.INVALID_RACING_CARS_SIZE; + +import java.util.List; +import java.util.stream.Collectors; + +public class RacingCars { + private static final int MIN_SIZE = 2; + private final List<RacingCar> racingCars; + private RacingCar maxDistanceCar; + + public RacingCars(List<RacingCar> racingCars) { + validateSize(racingCars); + validateDuplicated(racingCars); + this.racingCars = racingCars; + } + + private void validateSize(List<RacingCar> racingCars) { + if (racingCars.size() < MIN_SIZE) { + throw new IllegalArgumentException(INVALID_RACING_CARS_SIZE.getMessage()); + } + } + + private void validateDuplicated(List<RacingCar> racingCars) { + if (isDuplicated(racingCars)) { + throw new IllegalArgumentException(DUPLICATED_NAME.getMessage()); + } + } + + private boolean isDuplicated(List<RacingCar> racingCars) { + int sizeAfterCut = (int) racingCars.stream() + .distinct() + .count(); + return racingCars.size() != sizeAfterCut; + } + + public void startRace() { + racingCars + .forEach(racingCar -> + racingCar.moveForward(RandomNumberGenerator.generateRandomNumber())); + } + + public Winner selectWinner() { + findMaxDistanceCar(); + List<RacingCar> winner = racingCars.stream() + .filter(maxDistanceCar::isWinner) + .collect(Collectors.toList()); + return new Winner(winner); + } + + private void findMaxDistanceCar() { + maxDistanceCar = racingCars.stream() + .max(RacingCar::compareTo) + .orElseThrow(() -> new IllegalArgumentException(CANT_FIND_CAR.getMessage())); + } + + public List<RacingCar> getRacingCars() { + return racingCars; + } +}
Java
์ œ๊ฐ€ 3์ฃผ์ฐจ ๋ฏธ์…˜์„ ํ• ๋•Œ ๊ฒช์—ˆ๋˜ ์—๋กœ์‚ฌํ•ญ์ด ๋ฉ”์„œ๋“œ๋‚ด ๋ชจ๋“  ์ฝ”๋“œ๋ฅผ ์ถ•์•ฝ์„ ์‹œํ‚ค๋‹ค๋ณด๋‹ˆ ๋‚˜์ค‘์— ์ œ๊ฐ€ ๊ทธ ์ฝ”๋“œ๋ฅผ ๋ณด์•˜์„๋•Œ ๋ฌด์Šจ ์ฝ”๋“œ์ธ์ง€ ํ•œ๋ˆˆ์— ์•Œ๊ธฐ๊ฐ€ ํž˜๋“ค๋”๊ตฐ์š” ใ…œใ…œ ๊ทธ๋ž˜์„œ 4์ฃผ์ฐจ๋•Œ๋ถ€ํ„ฐ๋Š” ์–ด๋А์ •๋„ ์ ˆ์ œํ•ด์„œ ์ถ•์•ฝ์„ ํ•ด๋ณด๋‹ˆ ๊ฐ€๋…์„ฑ์ด ํ›จ์”ฌ ๋†’์•„์กŒ์—ˆ๋˜ ๊ฒฝํ—˜์ด ์žˆ์–ด์„œ ์ด๋ฒˆ์—๋„ ์ด๋Ÿฐ ๋ฐฉ์‹์œผ๋กœ ์ง„ํ–‰์„ ํ•ด๋ดค์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,38 @@ +package racingcar.view; + +import java.util.stream.Collectors; +import racingcar.domain.RacingCar; +import racingcar.domain.RacingCars; +import racingcar.domain.Winner; + +public class OutputView { + private static final String RACE_RESULT_MESSAGE = "\n์‹คํ–‰ ๊ฒฐ๊ณผ"; + private static final String DISTANCE_UNIT = "-"; + private static final String RACE_RESULT_FORMAT = "%s : %s%n"; + private static final String WINNER = "์ตœ์ข… ์šฐ์Šน์ž : "; + private static final String DELIMITER = ", "; + + public static void printRaceResultNotice() { + System.out.println(RACE_RESULT_MESSAGE); + } + + public static void printRaceResult(RacingCars racingCars) { + racingCars.getRacingCars() + .forEach(racingCar -> System.out.printf(RACE_RESULT_FORMAT + , racingCar.getCarName(), changeDistanceForm(racingCar.getDistance()))); + System.out.println(); + } + + private static String changeDistanceForm(int distance) { + return DISTANCE_UNIT.repeat(distance); + } + + public static void printWinner(Winner winner) { + System.out.print(WINNER); + String winners = winner.getWinner() + .stream() + .map(RacingCar::getCarName) + .collect(Collectors.joining(DELIMITER)); + System.out.println(winners); + } +}
Java
๋ฐ›์•„์˜จ ๋ฐ์ดํ„ฐ๋ฅผ ์–ด๋–ค์‹์œผ๋กœ ์ฒ˜๋ฆฌํ• ์ง€ ๊ฒฐ์ •ํ•˜๋Š” ๊ฒƒ์€ OutputView์˜ ์ฑ…์ž„์ด๋ผ๊ณ  ์ƒ๊ฐํ•ด์„œ ํ•ด๋‹น ๋ฐฉ์‹์œผ๋กœ ์ง„ํ–‰ํ–ˆ์Šต๋‹ˆ๋‹ค~ 3์ฃผ์ฐจ ๊ณตํ†ต ํ”ผ๋“œ๋ฐฑ์—์„œ๋„ view์—์„œ ์‚ฌ์šฉํ•˜๋Š” ๋ฐ์ดํ„ฐ๋Š” getter๋ฅผ ์‚ฌ์šฉํ•˜๋ผ๊ณ  ์–ธ๊ธ‰์ด ๋˜์–ด์žˆ๊ตฌ์š”! <img width="619" alt="image" src="https://github.com/parksangchu/java-racingcar-6/assets/142131857/99c1b2c6-7c6d-49ee-8154-e9d7c306bd0b">
@@ -0,0 +1,17 @@ +package racingcar.domain; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class CarNameTest { + @ParameterizedTest + @DisplayName("์ฐจ๋Ÿ‰์ด๋ฆ„์€ 1-5๊ธ€์ž์ด๊ณ  ํŠน์ˆ˜๋ฌธ์ž๋ฅผ ํฌํ•จํ•˜์ง€ ์•Š๋Š”๋‹ค.") + @ValueSource(strings = {"abcdef", "", "$", "&", " ", "!", "(", "$", "%"}) + void createCarName(String input) { + assertThatThrownBy(() -> new CarName(input)) + .isInstanceOf(IllegalArgumentException.class); + } +} \ No newline at end of file
Java
์ฒ˜์Œ ๋ณด๋Š” ๋ฉ”์„œ๋“œ์˜€๋Š”๋ฐ ํ•œ๋ฒˆ ์‚ฌ์šฉํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค! ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ใ…Žใ…Ž
@@ -0,0 +1,35 @@ +package racingcar.domain; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class RacingCarsTest { + @ParameterizedTest + @DisplayName("๊ฒฝ์ฃผ์—๋Š” ์ตœ์†Œ 2๋Œ€ ์ด์ƒ์˜ ์ฐจ๋Ÿ‰์ด ์ฐธ์—ฌํ•ด์•ผ ํ•˜๋ฉฐ ์ค‘๋ณต๋  ์ˆ˜ ์—†๋‹ค.") + @ValueSource(strings = {"์ƒ์ถ”", "์ƒ์ถ”,์ƒ์ถ”"}) + void createRacingCars(String input) { + List<RacingCar> racingCars = InputConvertor.convertToRacingCars(input); + assertThatThrownBy(() -> new RacingCars(racingCars)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("์šฐ์Šน์ž๋Š” ์ƒ์ถ”์™€ ๋ฐฐ์ถ”๋‹ค.") + void selectWinner() { + RacingCar sangchu = new RacingCar(new CarName("์ƒ์ถ”")); + RacingCar baechu = new RacingCar(new CarName("๋ฐฐ์ถ”")); + RacingCar moodosa = new RacingCar(new CarName("๋ฌด๋„์‚ฌ")); + RacingCars racingCars = new RacingCars(List.of(sangchu, baechu, moodosa)); + sangchu.moveForward(5); + baechu.moveForward(6); + Winner winner = racingCars.selectWinner(); + assertThat(winner.getWinner().get(0).getCarName()).isEqualTo("์ƒ์ถ”"); + assertThat(winner.getWinner().get(1).getCarName()).isEqualTo("๋ฐฐ์ถ”"); + } +} \ No newline at end of file
Java
์ฝ”๋“œ๋ฅผ ์ค„์ด๋ ค๊ณ  ๋„ˆ๋ฌด ์š•์‹ฌ์„ ๋‚ด๋‹ค๋ณด๋‹ˆ ๊ทธ๋งŒ ... ใ…œ ์•„๋ฌด๋ž˜๋„ ๋”ฐ๋กœ ํ…Œ์ŠคํŠธํ•˜๋Š”๊ฒŒ ๊ฐ€๋…์„ฑ ์ธก๋ฉด์—์„œ๋„ ์ข‹์„๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,17 @@ +package racingcar.domain; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class TurnTest { + @ParameterizedTest + @DisplayName("1ํšŒ ๋ฏธ๋งŒ, ์ˆซ์ž ์ด์™ธ ๊ฐ’ ์ž…๋ ฅ์‹œ ์˜ˆ์™ธ ๋ฐœ์ƒ") + @ValueSource(strings = {"0", "-1", "d", "#", "", " "}) + void createTurn(String input) { + assertThatThrownBy(() -> new Turn(input)) + .isInstanceOf(IllegalArgumentException.class); + } +} \ No newline at end of file
Java
์ €๋„ ์›๋ž˜๋Š” ๊ทธ๋Ÿฐ ๋ฐฉ์‹์œผ๋กœ ๊ฒ€์ฆ์„ ์ง„ํ–‰ํ•ด์˜ค๋‹ค๊ฐ€ ์ด๋ฒˆ์— 'InputView์—์„œ domain์—์„œ ์“ฐ์ผ ๋ฐ์ดํ„ฐ ํ˜•ํƒœ๋ฅผ ์•„๋Š”๊ฒŒ ๋งž์„๊นŒ?'ํ•˜๋Š” ์˜๋ฌธ์ด ๋“ค์–ด ํ•ด๋‹น ๋ฐฉ์‹์œผ๋กœ ์ง„ํ–‰์„ ํ•ด๋ดค์Šต๋‹ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  'RacingCar'์™€ ๊ฐ™์€ ํ•ด๋‹น ํ”„๋กœ๊ทธ๋žจ์˜ ๋„๋ฉ”์ธ์—์„œ ์“ฐ์ด๋Š” ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•ด์„œ ๋„˜๊ธฐ๋Š” ๊ฒƒ๋งŒ ์•„๋‹ˆ๋ผ๋ฉด int์™€ ๊ฐ™์€ ๊ธฐ๋ณธ๊ฐ’ ํ˜•ํƒœ๋Š” inputView์—์„œ ๊ฒ€์ฆํ•ด๋„ ๊ดœ์ฐฎ๊ฒ ๋‹ค๋ผ๋Š” ๊ฒฐ๋ก ์„ ๋ƒˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,11 @@ +package baseball.util; + +import java.util.Random; + +public class RamdomNumberGenerator { + private static final Random RANDOM = new Random(); + + public static Integer generate() { + return RANDOM.nextInt(9) + 1; + } +}
Java
๋ฌด์ž‘์œ„์˜ ์ˆซ์ž๋ฅผ ์ƒ์„ฑํ•˜๋Š” ํด๋ž˜์Šค๋ฅผ ๋”ฐ๋กœ ๋นผ์„œ ํ…Œ์ŠคํŠธ๋ฅผ ์šฉ์ดํ•˜๊ฒŒ ํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•œ ๊ฒŒ ์ข‹๋„ค์š”!
@@ -0,0 +1,101 @@ +package baseball.domain; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class NumericBalls implements Iterable { + private List<NumericBall> numericBalls; + + public NumericBalls() { + numericBalls = new ArrayList<>(); + } + + public NumericBalls(List<Integer> numbers) { + validate(numbers); + List<NumericBall> newBalls = new ArrayList<>(); + for (Integer number : numbers) { + newBalls.add(new NumericBall(number)); + } + this.numericBalls = newBalls; + } + + private void validate(List<Integer> numbers) { + if (numbers.size() != 3) { + throw new IllegalArgumentException(); + } + } + + public List<Integer> match(NumericBalls otherBalls) { + List<Integer> matchPoints = new ArrayList<>(); + int matchedCnt = matchBall(otherBalls); + int strikeCnt = strikeCheck(otherBalls); + matchPoints.add(strikeCnt); + matchPoints.add(matchedCnt - strikeCnt); + return matchPoints; + } + + private Integer matchBall(NumericBalls otherBalls) { + Map<Integer, Integer> map = new HashMap<>(); + for (NumericBall num : numericBalls) { + map.put(num.numericBall(), 0); + } + + int ballCnt = 0; + + Iterator otherIterator = otherBalls.iterator(); + while(otherIterator.hasNext()) { + NumericBall otherBall = otherIterator.next(); + if (map.containsKey(otherBall.numericBall())) { + map.put(otherBall.numericBall(), map.get(otherBall.numericBall()) + 1); + } + } + for (Integer value : map.values()) { + ballCnt += value; + } + return ballCnt; + } + + private Integer strikeCheck(NumericBalls otherBalls) { + int strikeCnt = 0; + for (int i = 0; i < numericBalls.size(); i++) { + if (numericBalls.get(i).equals(otherBalls.numericBall(i))) { + strikeCnt++; + } + } + return strikeCnt; + } + + public NumericBall numericBall(int index) { + return numericBalls.get(index); + } + + public int size() { + return numericBalls.size(); + } + + @Override + public Iterator iterator() { + return new NumericBallsIterator(this); + } + + private static class NumericBallsIterator implements Iterator { + private int index = 0; + private NumericBalls numericBalls; + + public NumericBallsIterator(NumericBalls numericBalls) { + this.numericBalls = numericBalls; + } + + @Override + public boolean hasNext() { + return (this.index < this.numericBalls.size()); + } + + @Override + public NumericBall next() { + return numericBalls.numericBall(this.index++); + } + } +}
Java
๋ฆฌ์ŠคํŠธ์— ๋„ฃ๊ณ  ๋งต์— ๋‹ค์‹œ ๋„ฃ๋Š” ๊ฒƒ๋ณด๋‹ค ์ฒ˜์Œ๋ถ€ํ„ฐ ํ•„๋“œ๋ฅผ ๋งต์œผ๋กœ ์„ ์–ธํ•˜๊ณ  ๋งต์˜ ์ˆซ์ž์™€ ์ธ๋ฑ์Šค๋ฅผ ๋น„๊ตํ•˜๋ฉด ํšจ์œจ์ด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,23 @@ +package baseball.view; + +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +public class InputView { + private static final Scanner SCANNER = new Scanner(System.in); + public static List<Integer> inputNumbers() { + System.out.println("์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š” : "); + List<Integer> nums = new ArrayList<>(); + nums.addAll(parse(List.of(SCANNER.next().split("")))); + return nums; + } + + private static List<Integer> parse(List<String> strArr) { + List<Integer> nums = new ArrayList<>(); + for (String str : strArr) { + nums.add(Integer.parseInt(str)); + } + return nums; + } +}
Java
๊ฐ์ฒด๋ฅผ ์ƒ์ˆ˜๋กœ ์„ ์–ธํ•˜๋ฉด ์ฝ”๋“œ๊ฐ€ ํ›จ์”ฌ ๊ฐ„ํŽธํ•ด์ง€์ง€๋งŒ, final์ž„์—๋„ ๊ฐ’์ด ๋ฐ”๋€” ์ˆ˜ ์žˆ์–ด ๊ด€๋ จ์ด์Šˆ๊ฐ€ ์žˆ์„ ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค. ์œ ์˜ํ•˜๊ณ  ์‚ฌ์šฉํ•ด์ฃผ์„ธ์š”:)
@@ -3,28 +3,50 @@ import './Login.scss'; import Login_Button from './Login_Button/Login_Button'; class Login extends Component { + constructor(props) { + super(props); + this.state = { + id: 'a', + pw: 0, + }; + } + + handleInput = e => { + const { value, name } = e.target; + this.setState({ + [name]: value, + }); + }; + render() { + const { handleInput } = this; + const { id, pw } = this.state; + return ( <div className="log_in_box"> <div className="title">westagram</div> <div className="log_in"> <div className="id"> <input + onChange={handleInput} className="id_input" + name="id" type="text" placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" /> </div> <div className="password"> <input + onChange={handleInput} className="password_input" + name="pw" type="password" placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" /> </div> </div> - <Login_Button /> + <Login_Button idvalue={this.state.id} pwvalue={this.state.pw} /> <p> ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”? </p> </div>
JavaScript
this.state ... ์ด๊ฑฐ ๋„ˆ๋ฌด ๊ธฐ๋‹ˆ๊นŒ ์ด๊ฒƒ๋„ ๋น„๊ตฌ์กฐํ™” ํ• ๋‹นํ•˜์‹œ๋Š” ๊ฒŒ ๊ฐ€๋…์„ฑ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -1,14 +1,51 @@ import React, { Component } from 'react'; +import Comment from './Comment/Comment'; import './Feeds.scss'; class Feeds extends Component { + constructor(props) { + super(props); + this.state = { + comment: '', + comments: [], + idnumber: 1, + }; + } + + componentDidMount = () => { + this.setState({ comments: this.props.comments }); + }; + + handleComment = e => { + this.setState({ + comment: e.target.value, + }); + }; + + addComment = e => { + e.preventDefault(); + + this.setState({ + comments: this.state.comments.concat({ + id: this.state.idnumber + 3, + text: this.state.comment, + }), + comment: '', + idnumber: this.state.idnumber + 1, + }); + }; + render() { + const { comments, comment } = this.state; + const { handleComment, addComment } = this; + // console.log(this.state); + return ( <div className="feeds"> <article> <div className="feeds_profile"> <div className="feeds_profile_image"> - <img alt="ํ”„๋กœํ•„" src="/images/jaesangChoi/profile1.jpeg" /> + <img alt="profile" src={this.props.profilesrc} /> </div> <p className="feeds_profile_name"> <span className="feeds_profile_main_name"> @@ -23,28 +60,28 @@ class Feeds extends Component { <img alt="sunset" className="main_feed_img" - src="https://images.unsplash.com/photo-1623659993428-0c5504a16ca5?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0Mnx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" + src={this.props.mainfeedsrc} /> </div> <div className="comment_icon_box"> <div className="left_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> <img - alt="์ฝ”๋ฉ˜ํŠธ์•„์ด์ฝ˜" + alt="comment_icon" src="/images/jaesangChoi/commentary.png" /> - <img alt="๊ณต์œ ์•„์ด์ฝ˜" src="/images/jaesangChoi/send.png" /> + <img alt="share_icon" src="/images/jaesangChoi/send.png" /> </div> <div className="right_icon"> - <img alt="๋ถ๋งˆํฌ์•„์ด์ฝ˜" src="/images/jaesangChoi/bookmark.png" /> + <img alt="bookmark_icon" src="/images/jaesangChoi/bookmark.png" /> </div> </div> <div className="comment_profile"> <div className="comment_profile_icon"> <img - alt="ํ”„๋กœํ•„" + alt="profile" src="/images/jaesangChoi/comment_profile.jpeg" /> </div> @@ -67,25 +104,33 @@ class Feeds extends Component { ์ข‹์•˜์ž–์•„~~~~~ </div> <div className="second_comment_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> </div> </div> <div className="third_comment">42๋ถ„ ์ „</div> + <ul className="comment_list"> + {comments.map(comment => { + return <Comment key={comment.id} text={comment.text} />; + })} + </ul> + <div className="push_comment"> <div className="push_comment_icon"> - <img alt="์Šค๋งˆ์ผ์•„์ด์ฝ˜" src="/images/jaesangChoi/smile.png" /> + <img alt="smile_icon" src="/images/jaesangChoi/smile.png" /> </div> - <div className="push_comment_text"> + <form className="push_comment_text" onSubmit={addComment}> <input + onChange={handleComment} + value={comment} className="input_comment" type="text" placeholder="๋Œ“๊ธ€๋‹ฌ๊ธฐ..." /> - </div> + </form> <div className="push_comment_button"> - <button>๊ฒŒ์‹œ</button> + <button onClick={addComment}>๊ฒŒ์‹œ</button> </div> </div> </article>
JavaScript
์—ฌ๊ธฐ form ํƒœ๊ทธ๋กœ ๊ฐ์‹ธ์‹œ๊ณ  onSubmit ์ด๋ฒคํŠธ์ฃผ์‹œ๋ฉด ์—”ํ„ฐํ‚ค ๋ˆ„๋ฅผ ๋•Œ ์‹คํ–‰๋˜๋Š” ๋ฉ”์†Œ๋“œ ๋”ฐ๋กœ ์•ˆ ๋งŒ๋“œ์…”๋„ pressButton ๋ฉ”์†Œ๋“œ ํ•˜๋‚˜๋งŒ์œผ๋กœ ๋Œ“๊ธ€ ์ถ”๊ฐ€์‹œํ‚ฌ ์ˆ˜ ์žˆ์–ด์š”!
@@ -3,28 +3,50 @@ import './Login.scss'; import Login_Button from './Login_Button/Login_Button'; class Login extends Component { + constructor(props) { + super(props); + this.state = { + id: 'a', + pw: 0, + }; + } + + handleInput = e => { + const { value, name } = e.target; + this.setState({ + [name]: value, + }); + }; + render() { + const { handleInput } = this; + const { id, pw } = this.state; + return ( <div className="log_in_box"> <div className="title">westagram</div> <div className="log_in"> <div className="id"> <input + onChange={handleInput} className="id_input" + name="id" type="text" placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" /> </div> <div className="password"> <input + onChange={handleInput} className="password_input" + name="pw" type="password" placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" /> </div> </div> - <Login_Button /> + <Login_Button idvalue={this.state.id} pwvalue={this.state.pw} /> <p> ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”? </p> </div>
JavaScript
๋ง์”€ํ•˜์‹ ๋Œ€๋กœ ๋ฐ”๊ฟจ์Šต๋‹ˆ๋‹ค!
@@ -1,14 +1,51 @@ import React, { Component } from 'react'; +import Comment from './Comment/Comment'; import './Feeds.scss'; class Feeds extends Component { + constructor(props) { + super(props); + this.state = { + comment: '', + comments: [], + idnumber: 1, + }; + } + + componentDidMount = () => { + this.setState({ comments: this.props.comments }); + }; + + handleComment = e => { + this.setState({ + comment: e.target.value, + }); + }; + + addComment = e => { + e.preventDefault(); + + this.setState({ + comments: this.state.comments.concat({ + id: this.state.idnumber + 3, + text: this.state.comment, + }), + comment: '', + idnumber: this.state.idnumber + 1, + }); + }; + render() { + const { comments, comment } = this.state; + const { handleComment, addComment } = this; + // console.log(this.state); + return ( <div className="feeds"> <article> <div className="feeds_profile"> <div className="feeds_profile_image"> - <img alt="ํ”„๋กœํ•„" src="/images/jaesangChoi/profile1.jpeg" /> + <img alt="profile" src={this.props.profilesrc} /> </div> <p className="feeds_profile_name"> <span className="feeds_profile_main_name"> @@ -23,28 +60,28 @@ class Feeds extends Component { <img alt="sunset" className="main_feed_img" - src="https://images.unsplash.com/photo-1623659993428-0c5504a16ca5?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0Mnx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" + src={this.props.mainfeedsrc} /> </div> <div className="comment_icon_box"> <div className="left_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> <img - alt="์ฝ”๋ฉ˜ํŠธ์•„์ด์ฝ˜" + alt="comment_icon" src="/images/jaesangChoi/commentary.png" /> - <img alt="๊ณต์œ ์•„์ด์ฝ˜" src="/images/jaesangChoi/send.png" /> + <img alt="share_icon" src="/images/jaesangChoi/send.png" /> </div> <div className="right_icon"> - <img alt="๋ถ๋งˆํฌ์•„์ด์ฝ˜" src="/images/jaesangChoi/bookmark.png" /> + <img alt="bookmark_icon" src="/images/jaesangChoi/bookmark.png" /> </div> </div> <div className="comment_profile"> <div className="comment_profile_icon"> <img - alt="ํ”„๋กœํ•„" + alt="profile" src="/images/jaesangChoi/comment_profile.jpeg" /> </div> @@ -67,25 +104,33 @@ class Feeds extends Component { ์ข‹์•˜์ž–์•„~~~~~ </div> <div className="second_comment_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> </div> </div> <div className="third_comment">42๋ถ„ ์ „</div> + <ul className="comment_list"> + {comments.map(comment => { + return <Comment key={comment.id} text={comment.text} />; + })} + </ul> + <div className="push_comment"> <div className="push_comment_icon"> - <img alt="์Šค๋งˆ์ผ์•„์ด์ฝ˜" src="/images/jaesangChoi/smile.png" /> + <img alt="smile_icon" src="/images/jaesangChoi/smile.png" /> </div> - <div className="push_comment_text"> + <form className="push_comment_text" onSubmit={addComment}> <input + onChange={handleComment} + value={comment} className="input_comment" type="text" placeholder="๋Œ“๊ธ€๋‹ฌ๊ธฐ..." /> - </div> + </form> <div className="push_comment_button"> - <button>๊ฒŒ์‹œ</button> + <button onClick={addComment}>๊ฒŒ์‹œ</button> </div> </div> </article>
JavaScript
form์— ์ด๋Ÿฐ ๊ธฐ๋Šฅ์ด ์žˆ๋Š” ์ค„ ์ฒ˜์Œ์•Œ์•˜์Šต๋‹ˆ๋‹ค! ๋•๋ถ„์— ์ƒˆ๋กœ์šด ์ง€์‹์„ ์–ป์—ˆ์Šต๋‹ˆ๋‹ค. ์ •๋ง ๊ฐ์‚ฌํ•ด์š”!
@@ -3,28 +3,50 @@ import './Login.scss'; import Login_Button from './Login_Button/Login_Button'; class Login extends Component { + constructor(props) { + super(props); + this.state = { + id: 'a', + pw: 0, + }; + } + + handleInput = e => { + const { value, name } = e.target; + this.setState({ + [name]: value, + }); + }; + render() { + const { handleInput } = this; + const { id, pw } = this.state; + return ( <div className="log_in_box"> <div className="title">westagram</div> <div className="log_in"> <div className="id"> <input + onChange={handleInput} className="id_input" + name="id" type="text" placeholder="์ „ํ™”๋ฒˆํ˜ธ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์ด๋ฉ”์ผ" /> </div> <div className="password"> <input + onChange={handleInput} className="password_input" + name="pw" type="password" placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ" /> </div> </div> - <Login_Button /> + <Login_Button idvalue={this.state.id} pwvalue={this.state.pw} /> <p> ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์žŠ์œผ์…จ๋‚˜์š”? </p> </div>
JavaScript
idValue๋ฅผ ๋„˜๊ฒจ์ฃผ๋Š” ๊ฑธ๋กœ ๋ณด์ด๋Š”๋ฐ idfunc๋ผ๋Š” ์ด๋ฆ„์€ ๋งˆ์น˜ ํ•จ์ˆ˜๊ฐ™์•„์„œ ์ ํ•ฉํ•˜์ง€ ์•Š์•„๋ณด์ž…๋‹ˆ๋‹ค! pwfunc, colorfunc ๋ชจ๋‘ ๋งˆ์ฐฌ๊ฐ€์ง€์ž…๋‹ˆ๋‹ค! ๊ทธ๋ฆฌ๊ณ  colorfunc๋ผ๋Š” ๊ฐ’์€ id๋ž‘ pwํ†ตํ•ด์„œ ๊ณ„์‚ฐ ๊ฐ€๋Šฅํ•ด๋ณด์ด๋Š”๋ฐ ๊ทธ๋Ÿฌ๋ฉด idValue๋ž‘ pwValue๋งŒ Props๋กœ ๋ฐ›๊ณ , colorfunc์—์„œ ๊ณ„์‚ฐ ํ•˜๋Š” ๊ฐ’์€ LoginButton ์ปดํฌ๋„ŒํŠธ์—์„œ propsํ†ตํ•ด์„œ ๋ฐ”๋กœ ๊ณ„์‚ฐํ•ด์„œ ์‚ฌ์šฉํ•ด๋„ ๋ฌด๋ฐฉํ•ด๋ณด์ž…๋‹ˆ๋‹ค!
@@ -1,14 +1,51 @@ import React, { Component } from 'react'; +import Comment from './Comment/Comment'; import './Feeds.scss'; class Feeds extends Component { + constructor(props) { + super(props); + this.state = { + comment: '', + comments: [], + idnumber: 1, + }; + } + + componentDidMount = () => { + this.setState({ comments: this.props.comments }); + }; + + handleComment = e => { + this.setState({ + comment: e.target.value, + }); + }; + + addComment = e => { + e.preventDefault(); + + this.setState({ + comments: this.state.comments.concat({ + id: this.state.idnumber + 3, + text: this.state.comment, + }), + comment: '', + idnumber: this.state.idnumber + 1, + }); + }; + render() { + const { comments, comment } = this.state; + const { handleComment, addComment } = this; + // console.log(this.state); + return ( <div className="feeds"> <article> <div className="feeds_profile"> <div className="feeds_profile_image"> - <img alt="ํ”„๋กœํ•„" src="/images/jaesangChoi/profile1.jpeg" /> + <img alt="profile" src={this.props.profilesrc} /> </div> <p className="feeds_profile_name"> <span className="feeds_profile_main_name"> @@ -23,28 +60,28 @@ class Feeds extends Component { <img alt="sunset" className="main_feed_img" - src="https://images.unsplash.com/photo-1623659993428-0c5504a16ca5?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0Mnx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" + src={this.props.mainfeedsrc} /> </div> <div className="comment_icon_box"> <div className="left_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> <img - alt="์ฝ”๋ฉ˜ํŠธ์•„์ด์ฝ˜" + alt="comment_icon" src="/images/jaesangChoi/commentary.png" /> - <img alt="๊ณต์œ ์•„์ด์ฝ˜" src="/images/jaesangChoi/send.png" /> + <img alt="share_icon" src="/images/jaesangChoi/send.png" /> </div> <div className="right_icon"> - <img alt="๋ถ๋งˆํฌ์•„์ด์ฝ˜" src="/images/jaesangChoi/bookmark.png" /> + <img alt="bookmark_icon" src="/images/jaesangChoi/bookmark.png" /> </div> </div> <div className="comment_profile"> <div className="comment_profile_icon"> <img - alt="ํ”„๋กœํ•„" + alt="profile" src="/images/jaesangChoi/comment_profile.jpeg" /> </div> @@ -67,25 +104,33 @@ class Feeds extends Component { ์ข‹์•˜์ž–์•„~~~~~ </div> <div className="second_comment_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> </div> </div> <div className="third_comment">42๋ถ„ ์ „</div> + <ul className="comment_list"> + {comments.map(comment => { + return <Comment key={comment.id} text={comment.text} />; + })} + </ul> + <div className="push_comment"> <div className="push_comment_icon"> - <img alt="์Šค๋งˆ์ผ์•„์ด์ฝ˜" src="/images/jaesangChoi/smile.png" /> + <img alt="smile_icon" src="/images/jaesangChoi/smile.png" /> </div> - <div className="push_comment_text"> + <form className="push_comment_text" onSubmit={addComment}> <input + onChange={handleComment} + value={comment} className="input_comment" type="text" placeholder="๋Œ“๊ธ€๋‹ฌ๊ธฐ..." /> - </div> + </form> <div className="push_comment_button"> - <button>๊ฒŒ์‹œ</button> + <button onClick={addComment}>๊ฒŒ์‹œ</button> </div> </div> </article>
JavaScript
api์ฃผ์†Œ๊ฐ€ data์•ˆ์— ๋“ค์–ด์žˆ๋Š” ํ˜•ํƒœ๋Š” ๋น„์ •์ƒ์ ์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! api์ฃผ์†Œ๋Š” ์ผ๋ฐ˜์ ์œผ๋กœ ๋ฐฑ์—”๋“œ์—์„œ ์ „์†กํ•ด์ฃผ์ง€ ์•Š์Šต๋‹ˆ๋‹ค! comment์ •๋ณด๋ž‘ feed์ •๋ณด๋ฅผ ๋ถ„๋ฆฌ์‹œ์ผœ๋†“์œผ์…”์„œ ๊ทธ๋Ÿฐ ๊ฒƒ ๊ฐ™์€๋ฐ, feed์•ˆ์— comment์ •๋ณด๋ฅผ ๊ทธ๋ƒฅ ๋‹ค ๋„ฃ์–ด์ฃผ์‹œ๋ฉด ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ``` { id: 1, profilesrc: '/images/jaesangChoi/profile1.jpeg', mainfeedsrc: 'https://images.unsplash.com/photo-1623659993428-0c5504a16ca5?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0Mnx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60', comment:["foo","bar"] }, ``` ์ด๋Ÿฐ์‹์œผ๋กœ์š”! ์ฝ”๋ฉ˜ํŠธ๋ž€ ์ •๋ณด๋Š” ํ”ผ๋“œ์— ์ข…์†๋˜์–ด ์žˆ๋Š” ์ •๋ณด๋‹ˆ๊นŒ ์ €๋Ÿฐ ํ˜•ํƒœ๊ฐ€ ์ ํ•ฉํ•ด๋ณด์ž…๋‹ˆ๋‹ค!
@@ -1,14 +1,51 @@ import React, { Component } from 'react'; +import Comment from './Comment/Comment'; import './Feeds.scss'; class Feeds extends Component { + constructor(props) { + super(props); + this.state = { + comment: '', + comments: [], + idnumber: 1, + }; + } + + componentDidMount = () => { + this.setState({ comments: this.props.comments }); + }; + + handleComment = e => { + this.setState({ + comment: e.target.value, + }); + }; + + addComment = e => { + e.preventDefault(); + + this.setState({ + comments: this.state.comments.concat({ + id: this.state.idnumber + 3, + text: this.state.comment, + }), + comment: '', + idnumber: this.state.idnumber + 1, + }); + }; + render() { + const { comments, comment } = this.state; + const { handleComment, addComment } = this; + // console.log(this.state); + return ( <div className="feeds"> <article> <div className="feeds_profile"> <div className="feeds_profile_image"> - <img alt="ํ”„๋กœํ•„" src="/images/jaesangChoi/profile1.jpeg" /> + <img alt="profile" src={this.props.profilesrc} /> </div> <p className="feeds_profile_name"> <span className="feeds_profile_main_name"> @@ -23,28 +60,28 @@ class Feeds extends Component { <img alt="sunset" className="main_feed_img" - src="https://images.unsplash.com/photo-1623659993428-0c5504a16ca5?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0Mnx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" + src={this.props.mainfeedsrc} /> </div> <div className="comment_icon_box"> <div className="left_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> <img - alt="์ฝ”๋ฉ˜ํŠธ์•„์ด์ฝ˜" + alt="comment_icon" src="/images/jaesangChoi/commentary.png" /> - <img alt="๊ณต์œ ์•„์ด์ฝ˜" src="/images/jaesangChoi/send.png" /> + <img alt="share_icon" src="/images/jaesangChoi/send.png" /> </div> <div className="right_icon"> - <img alt="๋ถ๋งˆํฌ์•„์ด์ฝ˜" src="/images/jaesangChoi/bookmark.png" /> + <img alt="bookmark_icon" src="/images/jaesangChoi/bookmark.png" /> </div> </div> <div className="comment_profile"> <div className="comment_profile_icon"> <img - alt="ํ”„๋กœํ•„" + alt="profile" src="/images/jaesangChoi/comment_profile.jpeg" /> </div> @@ -67,25 +104,33 @@ class Feeds extends Component { ์ข‹์•˜์ž–์•„~~~~~ </div> <div className="second_comment_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> </div> </div> <div className="third_comment">42๋ถ„ ์ „</div> + <ul className="comment_list"> + {comments.map(comment => { + return <Comment key={comment.id} text={comment.text} />; + })} + </ul> + <div className="push_comment"> <div className="push_comment_icon"> - <img alt="์Šค๋งˆ์ผ์•„์ด์ฝ˜" src="/images/jaesangChoi/smile.png" /> + <img alt="smile_icon" src="/images/jaesangChoi/smile.png" /> </div> - <div className="push_comment_text"> + <form className="push_comment_text" onSubmit={addComment}> <input + onChange={handleComment} + value={comment} className="input_comment" type="text" placeholder="๋Œ“๊ธ€๋‹ฌ๊ธฐ..." /> - </div> + </form> <div className="push_comment_button"> - <button>๊ฒŒ์‹œ</button> + <button onClick={addComment}>๊ฒŒ์‹œ</button> </div> </div> </article>
JavaScript
get method๋Š” ๊ธฐ๋ณธ๊ฐ’์ด๋ผ์„œ ๋”ฐ๋กœ ๊ธฐ์ž…์•ˆํ•ด์ฃผ์…”๋„ ๋ฉ๋‹ˆ๋‹ค!
@@ -1,14 +1,51 @@ import React, { Component } from 'react'; +import Comment from './Comment/Comment'; import './Feeds.scss'; class Feeds extends Component { + constructor(props) { + super(props); + this.state = { + comment: '', + comments: [], + idnumber: 1, + }; + } + + componentDidMount = () => { + this.setState({ comments: this.props.comments }); + }; + + handleComment = e => { + this.setState({ + comment: e.target.value, + }); + }; + + addComment = e => { + e.preventDefault(); + + this.setState({ + comments: this.state.comments.concat({ + id: this.state.idnumber + 3, + text: this.state.comment, + }), + comment: '', + idnumber: this.state.idnumber + 1, + }); + }; + render() { + const { comments, comment } = this.state; + const { handleComment, addComment } = this; + // console.log(this.state); + return ( <div className="feeds"> <article> <div className="feeds_profile"> <div className="feeds_profile_image"> - <img alt="ํ”„๋กœํ•„" src="/images/jaesangChoi/profile1.jpeg" /> + <img alt="profile" src={this.props.profilesrc} /> </div> <p className="feeds_profile_name"> <span className="feeds_profile_main_name"> @@ -23,28 +60,28 @@ class Feeds extends Component { <img alt="sunset" className="main_feed_img" - src="https://images.unsplash.com/photo-1623659993428-0c5504a16ca5?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0Mnx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" + src={this.props.mainfeedsrc} /> </div> <div className="comment_icon_box"> <div className="left_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> <img - alt="์ฝ”๋ฉ˜ํŠธ์•„์ด์ฝ˜" + alt="comment_icon" src="/images/jaesangChoi/commentary.png" /> - <img alt="๊ณต์œ ์•„์ด์ฝ˜" src="/images/jaesangChoi/send.png" /> + <img alt="share_icon" src="/images/jaesangChoi/send.png" /> </div> <div className="right_icon"> - <img alt="๋ถ๋งˆํฌ์•„์ด์ฝ˜" src="/images/jaesangChoi/bookmark.png" /> + <img alt="bookmark_icon" src="/images/jaesangChoi/bookmark.png" /> </div> </div> <div className="comment_profile"> <div className="comment_profile_icon"> <img - alt="ํ”„๋กœํ•„" + alt="profile" src="/images/jaesangChoi/comment_profile.jpeg" /> </div> @@ -67,25 +104,33 @@ class Feeds extends Component { ์ข‹์•˜์ž–์•„~~~~~ </div> <div className="second_comment_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> </div> </div> <div className="third_comment">42๋ถ„ ์ „</div> + <ul className="comment_list"> + {comments.map(comment => { + return <Comment key={comment.id} text={comment.text} />; + })} + </ul> + <div className="push_comment"> <div className="push_comment_icon"> - <img alt="์Šค๋งˆ์ผ์•„์ด์ฝ˜" src="/images/jaesangChoi/smile.png" /> + <img alt="smile_icon" src="/images/jaesangChoi/smile.png" /> </div> - <div className="push_comment_text"> + <form className="push_comment_text" onSubmit={addComment}> <input + onChange={handleComment} + value={comment} className="input_comment" type="text" placeholder="๋Œ“๊ธ€๋‹ฌ๊ธฐ..." /> - </div> + </form> <div className="push_comment_button"> - <button>๊ฒŒ์‹œ</button> + <button onClick={addComment}>๊ฒŒ์‹œ</button> </div> </div> </article>
JavaScript
๋Œ“๊ธ€์€ ๋‚˜์ค‘์— ์‚ญ์ œ๋  ์ˆ˜๋„ ์žˆ์œผ๋‹ˆ๊นŒ id๋ฅผ length๋กœ ์‚ฌ์šฉํ•˜๋ฉด ์‚ญ์ œ ํ›„ ๋‹ค์‹œ ์ถ”๊ฐ€๋˜๋Š” ๊ฒฝ์šฐ ๋™์ผํ•œ id๋ฅผ ๊ฐ€์ง„ ๋Œ“๊ธ€์ด ์ƒ๊ธธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -1,14 +1,51 @@ import React, { Component } from 'react'; +import Comment from './Comment/Comment'; import './Feeds.scss'; class Feeds extends Component { + constructor(props) { + super(props); + this.state = { + comment: '', + comments: [], + idnumber: 1, + }; + } + + componentDidMount = () => { + this.setState({ comments: this.props.comments }); + }; + + handleComment = e => { + this.setState({ + comment: e.target.value, + }); + }; + + addComment = e => { + e.preventDefault(); + + this.setState({ + comments: this.state.comments.concat({ + id: this.state.idnumber + 3, + text: this.state.comment, + }), + comment: '', + idnumber: this.state.idnumber + 1, + }); + }; + render() { + const { comments, comment } = this.state; + const { handleComment, addComment } = this; + // console.log(this.state); + return ( <div className="feeds"> <article> <div className="feeds_profile"> <div className="feeds_profile_image"> - <img alt="ํ”„๋กœํ•„" src="/images/jaesangChoi/profile1.jpeg" /> + <img alt="profile" src={this.props.profilesrc} /> </div> <p className="feeds_profile_name"> <span className="feeds_profile_main_name"> @@ -23,28 +60,28 @@ class Feeds extends Component { <img alt="sunset" className="main_feed_img" - src="https://images.unsplash.com/photo-1623659993428-0c5504a16ca5?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0Mnx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" + src={this.props.mainfeedsrc} /> </div> <div className="comment_icon_box"> <div className="left_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> <img - alt="์ฝ”๋ฉ˜ํŠธ์•„์ด์ฝ˜" + alt="comment_icon" src="/images/jaesangChoi/commentary.png" /> - <img alt="๊ณต์œ ์•„์ด์ฝ˜" src="/images/jaesangChoi/send.png" /> + <img alt="share_icon" src="/images/jaesangChoi/send.png" /> </div> <div className="right_icon"> - <img alt="๋ถ๋งˆํฌ์•„์ด์ฝ˜" src="/images/jaesangChoi/bookmark.png" /> + <img alt="bookmark_icon" src="/images/jaesangChoi/bookmark.png" /> </div> </div> <div className="comment_profile"> <div className="comment_profile_icon"> <img - alt="ํ”„๋กœํ•„" + alt="profile" src="/images/jaesangChoi/comment_profile.jpeg" /> </div> @@ -67,25 +104,33 @@ class Feeds extends Component { ์ข‹์•˜์ž–์•„~~~~~ </div> <div className="second_comment_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> </div> </div> <div className="third_comment">42๋ถ„ ์ „</div> + <ul className="comment_list"> + {comments.map(comment => { + return <Comment key={comment.id} text={comment.text} />; + })} + </ul> + <div className="push_comment"> <div className="push_comment_icon"> - <img alt="์Šค๋งˆ์ผ์•„์ด์ฝ˜" src="/images/jaesangChoi/smile.png" /> + <img alt="smile_icon" src="/images/jaesangChoi/smile.png" /> </div> - <div className="push_comment_text"> + <form className="push_comment_text" onSubmit={addComment}> <input + onChange={handleComment} + value={comment} className="input_comment" type="text" placeholder="๋Œ“๊ธ€๋‹ฌ๊ธฐ..." /> - </div> + </form> <div className="push_comment_button"> - <button>๊ฒŒ์‹œ</button> + <button onClick={addComment}>๊ฒŒ์‹œ</button> </div> </div> </article>
JavaScript
ํ•จ์ˆ˜๋Š” return๋ฌธ ๋”ฐ๋กœ ์—†์œผ๋ฉด ๋๊นŒ์ง€ ๋‹ค ์ฝ๊ณ ๋‚˜์„œ ์•Œ์•„์„œ ์ข…๋ฃŒ๋˜๊ธฐ๋•Œ๋ฌธ์— ์ž„์˜๋กœ return ํ‚ค์›Œ๋“œ๋ฅผ ์ ์„ ํ•„์š”๋Š” ์—†์–ด๋ณด์ž…๋‹ˆ๋‹ค!
@@ -1,14 +1,51 @@ import React, { Component } from 'react'; +import Comment from './Comment/Comment'; import './Feeds.scss'; class Feeds extends Component { + constructor(props) { + super(props); + this.state = { + comment: '', + comments: [], + idnumber: 1, + }; + } + + componentDidMount = () => { + this.setState({ comments: this.props.comments }); + }; + + handleComment = e => { + this.setState({ + comment: e.target.value, + }); + }; + + addComment = e => { + e.preventDefault(); + + this.setState({ + comments: this.state.comments.concat({ + id: this.state.idnumber + 3, + text: this.state.comment, + }), + comment: '', + idnumber: this.state.idnumber + 1, + }); + }; + render() { + const { comments, comment } = this.state; + const { handleComment, addComment } = this; + // console.log(this.state); + return ( <div className="feeds"> <article> <div className="feeds_profile"> <div className="feeds_profile_image"> - <img alt="ํ”„๋กœํ•„" src="/images/jaesangChoi/profile1.jpeg" /> + <img alt="profile" src={this.props.profilesrc} /> </div> <p className="feeds_profile_name"> <span className="feeds_profile_main_name"> @@ -23,28 +60,28 @@ class Feeds extends Component { <img alt="sunset" className="main_feed_img" - src="https://images.unsplash.com/photo-1623659993428-0c5504a16ca5?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0Mnx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" + src={this.props.mainfeedsrc} /> </div> <div className="comment_icon_box"> <div className="left_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> <img - alt="์ฝ”๋ฉ˜ํŠธ์•„์ด์ฝ˜" + alt="comment_icon" src="/images/jaesangChoi/commentary.png" /> - <img alt="๊ณต์œ ์•„์ด์ฝ˜" src="/images/jaesangChoi/send.png" /> + <img alt="share_icon" src="/images/jaesangChoi/send.png" /> </div> <div className="right_icon"> - <img alt="๋ถ๋งˆํฌ์•„์ด์ฝ˜" src="/images/jaesangChoi/bookmark.png" /> + <img alt="bookmark_icon" src="/images/jaesangChoi/bookmark.png" /> </div> </div> <div className="comment_profile"> <div className="comment_profile_icon"> <img - alt="ํ”„๋กœํ•„" + alt="profile" src="/images/jaesangChoi/comment_profile.jpeg" /> </div> @@ -67,25 +104,33 @@ class Feeds extends Component { ์ข‹์•˜์ž–์•„~~~~~ </div> <div className="second_comment_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> </div> </div> <div className="third_comment">42๋ถ„ ์ „</div> + <ul className="comment_list"> + {comments.map(comment => { + return <Comment key={comment.id} text={comment.text} />; + })} + </ul> + <div className="push_comment"> <div className="push_comment_icon"> - <img alt="์Šค๋งˆ์ผ์•„์ด์ฝ˜" src="/images/jaesangChoi/smile.png" /> + <img alt="smile_icon" src="/images/jaesangChoi/smile.png" /> </div> - <div className="push_comment_text"> + <form className="push_comment_text" onSubmit={addComment}> <input + onChange={handleComment} + value={comment} className="input_comment" type="text" placeholder="๋Œ“๊ธ€๋‹ฌ๊ธฐ..." /> - </div> + </form> <div className="push_comment_button"> - <button>๊ฒŒ์‹œ</button> + <button onClick={addComment}>๊ฒŒ์‹œ</button> </div> </div> </article>
JavaScript
์—ฌ๊ธฐ๋Š” alt๋ฅผ ํ•œ๊ธ€๋กœ ์ ๊ณ  ๋‹ค๋ฅธ ๊ณณ์€ ์˜์–ด๋กœ ์ ์œผ์‹  ์ด์œ ๊ฐ€ ์žˆ์œผ์‹ค๊นŒ์š”?? ์˜์–ด๋กœ ์ ์–ด์ฃผ์‹œ๋Š”๊ฒŒ ์ข‹์•„๋ณด์ž…๋‹ˆ๋‹ค! ํ•œ๊ธ€์ด ๋” ์ข‹์ง€๋งŒ,, ๋งŒ๊ตญ ๊ณต์šฉ์–ด๊ฐ€ ์˜์–ด๊ธฐ ๋•Œ๋ฌธ์— ๋ณดํŽธ์„ฑ์„ ์œ„ํ•ด์„œ ๐Ÿ˜‚
@@ -1,14 +1,51 @@ import React, { Component } from 'react'; +import Comment from './Comment/Comment'; import './Feeds.scss'; class Feeds extends Component { + constructor(props) { + super(props); + this.state = { + comment: '', + comments: [], + idnumber: 1, + }; + } + + componentDidMount = () => { + this.setState({ comments: this.props.comments }); + }; + + handleComment = e => { + this.setState({ + comment: e.target.value, + }); + }; + + addComment = e => { + e.preventDefault(); + + this.setState({ + comments: this.state.comments.concat({ + id: this.state.idnumber + 3, + text: this.state.comment, + }), + comment: '', + idnumber: this.state.idnumber + 1, + }); + }; + render() { + const { comments, comment } = this.state; + const { handleComment, addComment } = this; + // console.log(this.state); + return ( <div className="feeds"> <article> <div className="feeds_profile"> <div className="feeds_profile_image"> - <img alt="ํ”„๋กœํ•„" src="/images/jaesangChoi/profile1.jpeg" /> + <img alt="profile" src={this.props.profilesrc} /> </div> <p className="feeds_profile_name"> <span className="feeds_profile_main_name"> @@ -23,28 +60,28 @@ class Feeds extends Component { <img alt="sunset" className="main_feed_img" - src="https://images.unsplash.com/photo-1623659993428-0c5504a16ca5?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0Mnx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" + src={this.props.mainfeedsrc} /> </div> <div className="comment_icon_box"> <div className="left_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> <img - alt="์ฝ”๋ฉ˜ํŠธ์•„์ด์ฝ˜" + alt="comment_icon" src="/images/jaesangChoi/commentary.png" /> - <img alt="๊ณต์œ ์•„์ด์ฝ˜" src="/images/jaesangChoi/send.png" /> + <img alt="share_icon" src="/images/jaesangChoi/send.png" /> </div> <div className="right_icon"> - <img alt="๋ถ๋งˆํฌ์•„์ด์ฝ˜" src="/images/jaesangChoi/bookmark.png" /> + <img alt="bookmark_icon" src="/images/jaesangChoi/bookmark.png" /> </div> </div> <div className="comment_profile"> <div className="comment_profile_icon"> <img - alt="ํ”„๋กœํ•„" + alt="profile" src="/images/jaesangChoi/comment_profile.jpeg" /> </div> @@ -67,25 +104,33 @@ class Feeds extends Component { ์ข‹์•˜์ž–์•„~~~~~ </div> <div className="second_comment_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> </div> </div> <div className="third_comment">42๋ถ„ ์ „</div> + <ul className="comment_list"> + {comments.map(comment => { + return <Comment key={comment.id} text={comment.text} />; + })} + </ul> + <div className="push_comment"> <div className="push_comment_icon"> - <img alt="์Šค๋งˆ์ผ์•„์ด์ฝ˜" src="/images/jaesangChoi/smile.png" /> + <img alt="smile_icon" src="/images/jaesangChoi/smile.png" /> </div> - <div className="push_comment_text"> + <form className="push_comment_text" onSubmit={addComment}> <input + onChange={handleComment} + value={comment} className="input_comment" type="text" placeholder="๋Œ“๊ธ€๋‹ฌ๊ธฐ..." /> - </div> + </form> <div className="push_comment_button"> - <button>๊ฒŒ์‹œ</button> + <button onClick={addComment}>๊ฒŒ์‹œ</button> </div> </div> </article>
JavaScript
t๋ผ๋Š” ๋ณ€์ˆ˜๋ช…์„ ๊ฐ€์ง€๊ณ ๋Š” ์—ฌ๊ธฐ์— ํ• ๋‹น๋œ ๊ฐ’์ด ๋ญ์ผ์ง€ ์ „ํ˜€ ์œ ์ถ”๊ฐ€ ์•ˆ๋˜๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! comments ๋ฐฐ์—ด์•ˆ์˜ ํ•˜๋‚˜ํ•˜๋‚˜์˜ ์š”์†Œ๋“ค์ด๋‹ˆ๊นŒ comment๋ผ๊ณ  ์ด๋ฆ„์ง€์–ด์ฃผ๋Š”๊ฒŒ ์ข‹์ง€ ์•Š์„๊นŒ์š”? ```suggestion {comments.map(comment => { ```
@@ -1,14 +1,51 @@ import React, { Component } from 'react'; +import Comment from './Comment/Comment'; import './Feeds.scss'; class Feeds extends Component { + constructor(props) { + super(props); + this.state = { + comment: '', + comments: [], + idnumber: 1, + }; + } + + componentDidMount = () => { + this.setState({ comments: this.props.comments }); + }; + + handleComment = e => { + this.setState({ + comment: e.target.value, + }); + }; + + addComment = e => { + e.preventDefault(); + + this.setState({ + comments: this.state.comments.concat({ + id: this.state.idnumber + 3, + text: this.state.comment, + }), + comment: '', + idnumber: this.state.idnumber + 1, + }); + }; + render() { + const { comments, comment } = this.state; + const { handleComment, addComment } = this; + // console.log(this.state); + return ( <div className="feeds"> <article> <div className="feeds_profile"> <div className="feeds_profile_image"> - <img alt="ํ”„๋กœํ•„" src="/images/jaesangChoi/profile1.jpeg" /> + <img alt="profile" src={this.props.profilesrc} /> </div> <p className="feeds_profile_name"> <span className="feeds_profile_main_name"> @@ -23,28 +60,28 @@ class Feeds extends Component { <img alt="sunset" className="main_feed_img" - src="https://images.unsplash.com/photo-1623659993428-0c5504a16ca5?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw0Mnx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" + src={this.props.mainfeedsrc} /> </div> <div className="comment_icon_box"> <div className="left_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> <img - alt="์ฝ”๋ฉ˜ํŠธ์•„์ด์ฝ˜" + alt="comment_icon" src="/images/jaesangChoi/commentary.png" /> - <img alt="๊ณต์œ ์•„์ด์ฝ˜" src="/images/jaesangChoi/send.png" /> + <img alt="share_icon" src="/images/jaesangChoi/send.png" /> </div> <div className="right_icon"> - <img alt="๋ถ๋งˆํฌ์•„์ด์ฝ˜" src="/images/jaesangChoi/bookmark.png" /> + <img alt="bookmark_icon" src="/images/jaesangChoi/bookmark.png" /> </div> </div> <div className="comment_profile"> <div className="comment_profile_icon"> <img - alt="ํ”„๋กœํ•„" + alt="profile" src="/images/jaesangChoi/comment_profile.jpeg" /> </div> @@ -67,25 +104,33 @@ class Feeds extends Component { ์ข‹์•˜์ž–์•„~~~~~ </div> <div className="second_comment_icon"> - <img alt="ํ•˜ํŠธ์•„์ด์ฝ˜" src="/images/jaesangChoi/heart2.png" /> + <img alt="heart_icon" src="/images/jaesangChoi/heart2.png" /> </div> </div> <div className="third_comment">42๋ถ„ ์ „</div> + <ul className="comment_list"> + {comments.map(comment => { + return <Comment key={comment.id} text={comment.text} />; + })} + </ul> + <div className="push_comment"> <div className="push_comment_icon"> - <img alt="์Šค๋งˆ์ผ์•„์ด์ฝ˜" src="/images/jaesangChoi/smile.png" /> + <img alt="smile_icon" src="/images/jaesangChoi/smile.png" /> </div> - <div className="push_comment_text"> + <form className="push_comment_text" onSubmit={addComment}> <input + onChange={handleComment} + value={comment} className="input_comment" type="text" placeholder="๋Œ“๊ธ€๋‹ฌ๊ธฐ..." /> - </div> + </form> <div className="push_comment_button"> - <button>๊ฒŒ์‹œ</button> + <button onClick={addComment}>๊ฒŒ์‹œ</button> </div> </div> </article>
JavaScript
๋งˆ์ฐฌ๊ฐ€์ง€๋กœ pressButton์ด๋ผ๋Š” ์ด๋ฆ„๋งŒ ๋ณด๊ณ ๋Š” ์ „ํ˜€ ์œ ์ถ”๊ฐ€ ์•ˆ๋ฉ๋‹ˆ๋‹ค! pressButton์ด๋ผ๋Š”๊ฑด ๋ฐœ์ƒํ•˜๋Š” ์‹œ์ ์ด์ง€ ํ•จ์ˆ˜๊ฐ€ ํ•˜๊ณ ์žˆ๋Š” ๋™์ž‘์ด ์•„๋‹ˆ๊ธฐ ๋•Œ๋ฌธ์— ํ•จ์ˆ˜์˜ ์—ญํ• ์„ ๋™์‚ฌํ˜•์œผ๋กœ ๋ช…ํ™•ํ•˜๊ฒŒ addComment ๋“ฑ์œผ๋กœ ์ด๋ฆ„์ง€์–ด์ฃผ๋Š”๊ฒŒ ์ข‹์•„๋ณด์ž…๋‹ˆ๋‹ค!
@@ -5,15 +5,49 @@ import Main_right from './Main_right/Main_right'; import './Main.scss'; class Mainjaesang extends Component { + constructor(props) { + super(props); + this.state = { + feedslist: [], + }; + } + + callApi = () => { + fetch('http://localhost:3000/data/JaesangChoi/FeedsData.json') + .then(res => res.json()) + .then(data => { + this.setState({ + feedslist: data, + }); + }); + }; + + componentDidMount = () => { + this.callApi(); + }; + render() { + const { feedslist } = this.state; + return ( <div> <Nav /> + <main> + <div> + {feedslist.map(feed => { + return ( + <Feeds + key={feed.id} + profilesrc={feed.profilesrc} + mainfeedsrc={feed.mainfeedsrc} + comments={feed.comments} + /> + ); + })} + </div> - <div className="main"> - <Feeds /> <Main_right /> - </div> + </main> </div> ); }
JavaScript
feedslist์•ˆ์˜ ํ•˜๋‚˜์˜ ์š”์†Œ๋“ค์ธ๋ฐ flist๋ผ๋Š” ๋ณ€์ˆ˜๋ช…์€ ์ ํ•ฉํ•˜์ง€ ์•Š์€๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ์ฐจ๋ผ๋ฆฌ feed๋“ฑ์ด ์ข€ ๋” ์ ํ•ฉํ•˜๊ณ  ์˜๋ฏธ๊ฐ€ ๋“œ๋Ÿฌ๋‚˜ ๋ณด์ด๋„ค์š”!
@@ -5,15 +5,49 @@ import Main_right from './Main_right/Main_right'; import './Main.scss'; class Mainjaesang extends Component { + constructor(props) { + super(props); + this.state = { + feedslist: [], + }; + } + + callApi = () => { + fetch('http://localhost:3000/data/JaesangChoi/FeedsData.json') + .then(res => res.json()) + .then(data => { + this.setState({ + feedslist: data, + }); + }); + }; + + componentDidMount = () => { + this.callApi(); + }; + render() { + const { feedslist } = this.state; + return ( <div> <Nav /> + <main> + <div> + {feedslist.map(feed => { + return ( + <Feeds + key={feed.id} + profilesrc={feed.profilesrc} + mainfeedsrc={feed.mainfeedsrc} + comments={feed.comments} + /> + ); + })} + </div> - <div className="main"> - <Feeds /> <Main_right /> - </div> + </main> </div> ); }
JavaScript
๋ฉ”์ธ ์ฝ˜ํ…์ธ  ๊ตฌํš์„ ์˜๋ฏธํ•˜๋Š” ๊ฑฐ๋ผ๋ฉด div tag๋ณด๋‹ค๋Š” main tag๊ฐ€ ์ข€ ๋” ์ ํ•ฉํ•˜์ง€ ์•Š์„๊นŒ์š”?
@@ -1,31 +1,15 @@ - - -body { - margin: 0px; - overflow: hidden; - +main { + display: flex; + justify-content: center; + gap: 20px; + padding-top: 54px; + box-sizing: border-box; + + .bold_comment { + font-weight: bold; + } + + .grey_comment { + color: grey; + } } - - - -.main { - display: flex; - justify-content: center; - gap: 20px; - width:100%; - height:100vh; - padding-top: 54px; - box-sizing: border-box; - overflow: auto; - - .bold_comment { - font-weight:bold; - } - - .grey_comment { - color: grey; - } - -} - -
Unknown
์ด๋ฏธ display:block์ธ ์š”์†Œ์ธ๋ฐ width:100% ๋ฅผ ๋ถ€์—ฌํ•  ์ด์œ ๊ฐ€ ์—†์–ด๋ณด์ž…๋‹ˆ๋‹ค!
@@ -1,31 +1,15 @@ - - -body { - margin: 0px; - overflow: hidden; - +main { + display: flex; + justify-content: center; + gap: 20px; + padding-top: 54px; + box-sizing: border-box; + + .bold_comment { + font-weight: bold; + } + + .grey_comment { + color: grey; + } } - - - -.main { - display: flex; - justify-content: center; - gap: 20px; - width:100%; - height:100vh; - padding-top: 54px; - box-sizing: border-box; - overflow: auto; - - .bold_comment { - font-weight:bold; - } - - .grey_comment { - color: grey; - } - -} - -
Unknown
height:100vh๋กœ ๋ถ€๋ชจํƒœ๊ทธ์˜ ํฌ๊ธฐ๋ฅผ ๊ณ ์ •๊ฐ’์œผ๋กœ ์ •ํ•˜๋Š”๊ฑด ์ข‹์ง€์•Š์Šต๋‹ˆ๋‹ค! ๋ถ€๋ชจํƒœ๊ทธ์— ๊ณ ์ •๋†’์ด๊ฐ’์„ ์ฃผ๋Š”๊ฑด ์Šคํฌ๋กค์ด ํ•„์š”ํ•œ ๊ฒฝ์šฐ๋ฅผ ์ œ์™ธํ•˜๊ณ ๋Š” ์ง€์–‘ํ•˜๊ณ ์žˆ์Šต๋‹ˆ๋‹ค! ์•ˆ์— ์—ฌ๋Ÿฌ ์ž์‹ํƒœ๊ทธ๋“ค์ด ๋“ค์–ด์˜ฌํ…๋ฐ ๊ทธ ํฌ๊ธฐ๋งŒํผ ์ž์—ฐ์Šค๋Ÿฝ๊ฒŒ ๋Š˜์–ด๋‚˜๋„๋ก height๊ฐ’์„ ์ฃผ์ง€ ์•Š๋Š”๊ฒŒ ์ข‹์•„๋ณด์ž…๋‹ˆ๋‹ค!
@@ -1,9 +1,25 @@ import React, { Component } from 'react'; -import Recommendation_list from './Recommendation_list/Recommendation_list'; +import RecommendationList from './Recommendation_list/Recommendation_list'; +import RECOMMENDATION_DATA from './RecommendationData'; import './Main_right.scss'; class Main_right extends Component { + constructor(props) { + super(props); + this.state = { + recommendation_List: [], + }; + } + + componentDidMount() { + this.setState({ + recommendation_List: RECOMMENDATION_DATA, + }); + } + render() { + const { recommendation_List } = this.state; + return ( <div className="main_right"> <div className="my_profile"> @@ -26,29 +42,18 @@ class Main_right extends Component { <p className="bold_comment">๋ชจ๋‘ ๋ณด๊ธฐ</p> </div> - <Recommendation_list - src="/images/jaesangChoi/profile3.jpeg" - main_name="musttafa_dgn" - sub_name="adnankizlitas๋‹˜ ์™ธ 6๋ช…์ด ํŒ”๋กœ์šฐํ•ฉ๋‹ˆ๋‹ค" - /> - - <Recommendation_list - src="/images/jaesangChoi/profile4.jpeg" - main_name="rah6590" - sub_name="ํšŒ์›๋‹˜์„ ํŒ”๋กœ์šฐํ•ฉ๋‹ˆ๋‹ค" - /> - - <Recommendation_list - src="https://images.unsplash.com/photo-1547656807-9733c2b738c2?ixid=MnwxMjA3fDF8MHxlZGl0b3JpYWwtZmVlZHwxfHx8ZW58MHx8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" - main_name="sym.ysl" - sub_name="gizoo_๋‹˜ ์™ธ 1๋ช…์ด ํŒ”๋กœ์šฐํ•ฉ๋‹ˆ๋‹ค" - /> - - <Recommendation_list - src="https://images.unsplash.com/photo-1623720274043-841b674a1a52?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw5fHx8ZW58MHx8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" - main_name="serdarakyol67" - sub_name="buse.19987๋‹˜ ์™ธ 1๋ช…์ด ํŒ”๋กœ์šฐํ•จ" - /> + <ul> + {recommendation_List.map(list => { + return ( + <RecommendationList + key={list.id} + src={list.src} + main_name={list.main_name} + sub_name={list.sub_name} + /> + ); + })} + </ul> </div> <p className="etc">
JavaScript
์ƒ์ˆ˜๋ฐ์ดํ„ฐ๋Š” ๋Œ€๋ฌธ์ž + snake_case ์‚ฌ์šฉํ•ด์ฃผ์„ธ์š”!
@@ -1,9 +1,25 @@ import React, { Component } from 'react'; -import Recommendation_list from './Recommendation_list/Recommendation_list'; +import RecommendationList from './Recommendation_list/Recommendation_list'; +import RECOMMENDATION_DATA from './RecommendationData'; import './Main_right.scss'; class Main_right extends Component { + constructor(props) { + super(props); + this.state = { + recommendation_List: [], + }; + } + + componentDidMount() { + this.setState({ + recommendation_List: RECOMMENDATION_DATA, + }); + } + render() { + const { recommendation_List } = this.state; + return ( <div className="main_right"> <div className="my_profile"> @@ -26,29 +42,18 @@ class Main_right extends Component { <p className="bold_comment">๋ชจ๋‘ ๋ณด๊ธฐ</p> </div> - <Recommendation_list - src="/images/jaesangChoi/profile3.jpeg" - main_name="musttafa_dgn" - sub_name="adnankizlitas๋‹˜ ์™ธ 6๋ช…์ด ํŒ”๋กœ์šฐํ•ฉ๋‹ˆ๋‹ค" - /> - - <Recommendation_list - src="/images/jaesangChoi/profile4.jpeg" - main_name="rah6590" - sub_name="ํšŒ์›๋‹˜์„ ํŒ”๋กœ์šฐํ•ฉ๋‹ˆ๋‹ค" - /> - - <Recommendation_list - src="https://images.unsplash.com/photo-1547656807-9733c2b738c2?ixid=MnwxMjA3fDF8MHxlZGl0b3JpYWwtZmVlZHwxfHx8ZW58MHx8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" - main_name="sym.ysl" - sub_name="gizoo_๋‹˜ ์™ธ 1๋ช…์ด ํŒ”๋กœ์šฐํ•ฉ๋‹ˆ๋‹ค" - /> - - <Recommendation_list - src="https://images.unsplash.com/photo-1623720274043-841b674a1a52?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw5fHx8ZW58MHx8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" - main_name="serdarakyol67" - sub_name="buse.19987๋‹˜ ์™ธ 1๋ช…์ด ํŒ”๋กœ์šฐํ•จ" - /> + <ul> + {recommendation_List.map(list => { + return ( + <RecommendationList + key={list.id} + src={list.src} + main_name={list.main_name} + sub_name={list.sub_name} + /> + ); + })} + </ul> </div> <p className="etc">
JavaScript
camelCase ์‚ฌ์šฉํ•ด์ฃผ์„ธ์š”! ์ง€๊ธˆ์€ pascalCase๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  ๊ณ„์‹œ๋„ค์š”!
@@ -1,9 +1,25 @@ import React, { Component } from 'react'; -import Recommendation_list from './Recommendation_list/Recommendation_list'; +import RecommendationList from './Recommendation_list/Recommendation_list'; +import RECOMMENDATION_DATA from './RecommendationData'; import './Main_right.scss'; class Main_right extends Component { + constructor(props) { + super(props); + this.state = { + recommendation_List: [], + }; + } + + componentDidMount() { + this.setState({ + recommendation_List: RECOMMENDATION_DATA, + }); + } + render() { + const { recommendation_List } = this.state; + return ( <div className="main_right"> <div className="my_profile"> @@ -26,29 +42,18 @@ class Main_right extends Component { <p className="bold_comment">๋ชจ๋‘ ๋ณด๊ธฐ</p> </div> - <Recommendation_list - src="/images/jaesangChoi/profile3.jpeg" - main_name="musttafa_dgn" - sub_name="adnankizlitas๋‹˜ ์™ธ 6๋ช…์ด ํŒ”๋กœ์šฐํ•ฉ๋‹ˆ๋‹ค" - /> - - <Recommendation_list - src="/images/jaesangChoi/profile4.jpeg" - main_name="rah6590" - sub_name="ํšŒ์›๋‹˜์„ ํŒ”๋กœ์šฐํ•ฉ๋‹ˆ๋‹ค" - /> - - <Recommendation_list - src="https://images.unsplash.com/photo-1547656807-9733c2b738c2?ixid=MnwxMjA3fDF8MHxlZGl0b3JpYWwtZmVlZHwxfHx8ZW58MHx8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" - main_name="sym.ysl" - sub_name="gizoo_๋‹˜ ์™ธ 1๋ช…์ด ํŒ”๋กœ์šฐํ•ฉ๋‹ˆ๋‹ค" - /> - - <Recommendation_list - src="https://images.unsplash.com/photo-1623720274043-841b674a1a52?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw5fHx8ZW58MHx8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" - main_name="serdarakyol67" - sub_name="buse.19987๋‹˜ ์™ธ 1๋ช…์ด ํŒ”๋กœ์šฐํ•จ" - /> + <ul> + {recommendation_List.map(list => { + return ( + <RecommendationList + key={list.id} + src={list.src} + main_name={list.main_name} + sub_name={list.sub_name} + /> + ); + })} + </ul> </div> <p className="etc">
JavaScript
camelCase ์‚ฌ์šฉํ•ด์ฃผ์„ธ์š”!
@@ -1,31 +1,15 @@ - - -body { - margin: 0px; - overflow: hidden; - +main { + display: flex; + justify-content: center; + gap: 20px; + padding-top: 54px; + box-sizing: border-box; + + .bold_comment { + font-weight: bold; + } + + .grey_comment { + color: grey; + } } - - - -.main { - display: flex; - justify-content: center; - gap: 20px; - width:100%; - height:100vh; - padding-top: 54px; - box-sizing: border-box; - overflow: auto; - - .bold_comment { - font-weight:bold; - } - - .grey_comment { - color: grey; - } - -} - -
Unknown
main.scss์—์„œ mainํƒœ๊ทธ์— height: 100vh๋ฅผ ์ค€ ์ด์œ ๊ฐ€ ํ™”๋ฉด ์ „์ฒด๋ฅผ ๋ฒ”์œ„๋ฅผ ๊ฐ–๊ฒŒ ํ•ด์ฃผ๋ ค๊ณ  ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค. ๊ทธ ์ด์œ ๋Š” Main_right์˜ ๋ฐ•์Šค๊ฐ€ Nav์ฒ˜๋Ÿผ ๊ณ ์ •๋œ๊ฑธ ๊ตฌํ˜„ํ•˜๋ ค๊ณ  ํ–ˆ๊ณ  ๊ทธ ๋ฐฉ๋ฒ•์œผ๋กœ position:sticky๊ฐ€ ๋– ์˜ฌ๋ž๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค. sticky๋กœ ํ™”๋ฉด์— ๊ณ„์† ๊ณ ์ •์‹œํ‚ค๊ธฐ ์œ„ํ•ด์„  ํ™”๋ฉด ์ „์ฒด์— ๋Œ€ํ•ด์„œ ๋ฒ”์œ„๋ฅผ ๊ฐ€์ ธ์•ผํ•˜๋Š”๋ฐ Main_right๋Š” mainํƒœ๊ทธ์˜ ์ž์‹์ด๊ธฐ ๋•Œ๋ฌธ์— mainํƒœ๊ทธ๊ฐ€ ํ™”๋ฉด์ „์ฒด์˜ ๋ฒ”์œ„๋ฅผ ๊ฐ€์ ธ์•ผ ํ–ˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜์„œ main์— height:100vh๋ฅผ ์คฌ์Šต๋‹ˆ๋‹ค์•„... height๋ฅผ auto๋กœ ์„ค์ •ํ•˜๋ฉด position:sticky๊ฐ€ ์ •์ƒ์ ์œผ๋กœ ์ž‘๋™ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค ใ… ใ… ;
@@ -1,31 +1,15 @@ - - -body { - margin: 0px; - overflow: hidden; - +main { + display: flex; + justify-content: center; + gap: 20px; + padding-top: 54px; + box-sizing: border-box; + + .bold_comment { + font-weight: bold; + } + + .grey_comment { + color: grey; + } } - - - -.main { - display: flex; - justify-content: center; - gap: 20px; - width:100%; - height:100vh; - padding-top: 54px; - box-sizing: border-box; - overflow: auto; - - .bold_comment { - font-weight:bold; - } - - .grey_comment { - color: grey; - } - -} - -
Unknown
๋ผ์šด์ง€์— ๊ณ„์‹ค ๋•Œ ์—ฌ์ญค๋ณด๊ธธ ์ž˜ํ•œ๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๋•๋ถ„์— position:sticky์— ๋Œ€ํ•ด์„œ ์ฐฉ๊ฐํ–ˆ๋˜๊ฒŒ ์™„์ „ํžˆ ์žกํ˜”์Šต๋‹ˆ๋‹ค. ๋”์ด์ƒ position์€ ๋‘๋ ต์ง€ ์•Š๋„ค์š”!!!
@@ -0,0 +1,14 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <link rel="icon" type="image/svg+xml" href="/vite.svg" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <title>react-shopping-products</title> + <script type="module" crossorigin src="/react-shopping-products/dist/assets/index-B5NHo3G9.js"></script> + <link rel="stylesheet" crossorigin href="/react-shopping-products/dist/assets/index-BlzNY9oW.css"> + </head> + <body> + <div id="root"></div> + </body> +</html>
Unknown
dist ํด๋”๊ฐ€ git ignore๋˜์ง€ ์•Š์•˜๊ตฐ์šฉ
@@ -0,0 +1,10 @@ +/** + * generateBasicToken - Basic auth๋ฅผ ์œ„ํ•œ ํ† ํฐ์„ ๋งŒ๋“œ๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค. + * @param {string} userId - USERNAME์ž…๋‹ˆ๋‹ค. + * @param {string} userPassword - PASSWORD์ž…๋‹ˆ๋‹ค. + * @returns {string} + */ +export function generateBasicToken(userId: string, userPassword: string): string { + const token = btoa(`${userId}:${userPassword}`); + return `Basic ${token}`; +}
TypeScript
์„ฌ์„ธํ•œ jsdocs ๐Ÿ‘๐Ÿ‘๐Ÿ‘๐Ÿ‘
@@ -0,0 +1,95 @@ +import { CartItemType, ProductType } from '../types'; +import { generateBasicToken } from './auth'; + +const API_URL = import.meta.env.VITE_API_URL; +const USER_ID = import.meta.env.VITE_USER_ID; +const USER_PASSWORD = import.meta.env.VITE_USER_PASSWORD; + +/** + * ๊ณตํ†ต ์š”์ฒญ์„ ์ฒ˜๋ฆฌํ•˜๋Š” ํ•จ์ˆ˜ + * @param {string} endpoint - API endpoint + * @param {RequestInit} options - fetch options + * @returns {Response} - fetch response + */ +async function makeRequest(endpoint: string, options: RequestInit): Promise<Response> { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + + const response = await fetch(`${API_URL}${endpoint}`, { + ...options, + headers: { + ...options.headers, + Authorization: token, + 'Content-Type': 'application/json', + }, + }); + + if (!response.ok) { + throw new Error(`Failed to ${options.method?.toLowerCase()} ${endpoint}`); + } + + return response; +} + +interface FetchProductsParams { + category?: string; + page?: number; + size?: number; + sort?: string; +} + +/** + * fetchCartItems - API์—์„œ ์ƒํ’ˆ ๋ชฉ๋ก์„ fetchํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<ProductType[]>} + */ +export async function fetchProducts(params: FetchProductsParams = {}): Promise<ProductType[]> { + const queryString = Object.entries(params) + .map(([key, value]) => { + if (key === 'category' && value === 'all') { + return; + } else { + return `${key}=${value}`; + } + }) + .join('&'); + const response = await makeRequest(`/products?${queryString}`, { + method: 'GET', + }); + const data = await response.json(); + + return data.content; +} + +/** + * addCartItem - ์„ ํƒํ•œ ์ƒํ’ˆ์„ ์žฅ๋ฐ”๊ตฌ๋‹ˆ์— ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<void>} + */ +export async function addCartItem(productId: number): Promise<void> { + await makeRequest('/cart-items', { + method: 'POST', + body: JSON.stringify({ productId }), + }); +} + +/** + * fetchCartItem - API์—์„œ ์žฅ๋ฐ”๊ตฌ๋‹ˆ ๋ชฉ๋ก์„ fetchํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<CartItemType[]>} + */ +export async function fetchCartItem(): Promise<CartItemType[]> { + const response = await makeRequest('/cart-items?page=0&size=100', { + method: 'GET', + }); + + const data = await response.json(); + + return data.content; +} + +/** + * deleteCartItem - ์„ ํƒํ•œ ์ƒํ’ˆ์„ ์žฅ๋ฐ”๊ตฌ๋‹ˆ์—์„œ ์‚ญ์ œํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<void>} + */ +export async function deleteCartItem(cartItemId: number): Promise<void> { + await makeRequest(`/cart-items/${cartItemId}`, { + method: 'DELETE', + }); +}
TypeScript
๊ณตํ†ต ๋กœ์ง์„ ๋ฌถ์–ด์ฃผ๋Š” ๊ฒƒ ๋„ˆ๋ฌด ์ข‹์Šต๋‹ˆ๋‹ค~!
@@ -0,0 +1,95 @@ +import { CartItemType, ProductType } from '../types'; +import { generateBasicToken } from './auth'; + +const API_URL = import.meta.env.VITE_API_URL; +const USER_ID = import.meta.env.VITE_USER_ID; +const USER_PASSWORD = import.meta.env.VITE_USER_PASSWORD; + +/** + * ๊ณตํ†ต ์š”์ฒญ์„ ์ฒ˜๋ฆฌํ•˜๋Š” ํ•จ์ˆ˜ + * @param {string} endpoint - API endpoint + * @param {RequestInit} options - fetch options + * @returns {Response} - fetch response + */ +async function makeRequest(endpoint: string, options: RequestInit): Promise<Response> { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + + const response = await fetch(`${API_URL}${endpoint}`, { + ...options, + headers: { + ...options.headers, + Authorization: token, + 'Content-Type': 'application/json', + }, + }); + + if (!response.ok) { + throw new Error(`Failed to ${options.method?.toLowerCase()} ${endpoint}`); + } + + return response; +} + +interface FetchProductsParams { + category?: string; + page?: number; + size?: number; + sort?: string; +} + +/** + * fetchCartItems - API์—์„œ ์ƒํ’ˆ ๋ชฉ๋ก์„ fetchํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<ProductType[]>} + */ +export async function fetchProducts(params: FetchProductsParams = {}): Promise<ProductType[]> { + const queryString = Object.entries(params) + .map(([key, value]) => { + if (key === 'category' && value === 'all') { + return; + } else { + return `${key}=${value}`; + } + }) + .join('&'); + const response = await makeRequest(`/products?${queryString}`, { + method: 'GET', + }); + const data = await response.json(); + + return data.content; +} + +/** + * addCartItem - ์„ ํƒํ•œ ์ƒํ’ˆ์„ ์žฅ๋ฐ”๊ตฌ๋‹ˆ์— ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<void>} + */ +export async function addCartItem(productId: number): Promise<void> { + await makeRequest('/cart-items', { + method: 'POST', + body: JSON.stringify({ productId }), + }); +} + +/** + * fetchCartItem - API์—์„œ ์žฅ๋ฐ”๊ตฌ๋‹ˆ ๋ชฉ๋ก์„ fetchํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<CartItemType[]>} + */ +export async function fetchCartItem(): Promise<CartItemType[]> { + const response = await makeRequest('/cart-items?page=0&size=100', { + method: 'GET', + }); + + const data = await response.json(); + + return data.content; +} + +/** + * deleteCartItem - ์„ ํƒํ•œ ์ƒํ’ˆ์„ ์žฅ๋ฐ”๊ตฌ๋‹ˆ์—์„œ ์‚ญ์ œํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<void>} + */ +export async function deleteCartItem(cartItemId: number): Promise<void> { + await makeRequest(`/cart-items/${cartItemId}`, { + method: 'DELETE', + }); +}
TypeScript
์žฅ๋ฐ”๊ตฌ๋‹ˆ์— 100๊ฐœ ๋„˜๊ฒŒ ๋‹ด์„ ์ˆ˜ ์žˆ๋Š” case๊ฐ€ ์กด์žฌํ•  ๊ฒƒ ๊ฐ™์•„์š”~!
@@ -0,0 +1,50 @@ +.loaderContainer { + height: 60px; + display: flex; + justify-content: center; + align-items: center; +} + +.loader { + width: 60px; + display: flex; + justify-content: space-evenly; +} + +.ball { + list-style: none; + width: 12px; + height: 12px; + border-radius: 50%; + background-color: black; +} + +.ball:nth-child(1) { + animation: bounce1 0.4s ease-in-out infinite; +} + +@keyframes bounce1 { + 50% { + transform: translateY(-18px); + } +} + +.ball:nth-child(2) { + animation: bounce2 0.4s ease-in-out 0.2s infinite; +} + +@keyframes bounce2 { + 50% { + transform: translateY(-18px); + } +} + +.ball:nth-child(3) { + animation: bounce3 0.4s ease-in-out 0.4s infinite; +} + +@keyframes bounce3 { + 50% { + transform: translateY(-18px); + } +}
Unknown
๊ท€์—ฌ์šด ์• ๋‹ˆ๋ฉ”์ด์…˜์„ ๋งŒ๋“ค์—ˆ๊ตฐ์šฉ ๐Ÿš€๐Ÿš€๐Ÿš€
@@ -0,0 +1,15 @@ +export const productCategories = { + all: '์ „์ฒด', + fashion: 'ํŒจ์…˜', + beverage: '์Œ๋ฃŒ', + electronics: '์ „์ž์ œํ’ˆ', + kitchen: '์ฃผ๋ฐฉ์šฉํ’ˆ', + fitness: 'ํ”ผํŠธ๋‹ˆ์Šค', + books: '๋„์„œ', +} as const; + +export const sortOptions = { priceAsc: '๋‚ฎ์€ ๊ฐ€๊ฒฉ์ˆœ', priceDesc: '๋†’์€ ๊ฐ€๊ฒฉ์ˆœ' } as const; + +export const FIRST_FETCH_PAGE = 0; +export const FIRST_FETCH_SIZE = 20; +export const AFTER_FETCH_SIZE = 4;
TypeScript
์ƒ์ˆ˜ํ™” ๐Ÿ‘๐Ÿ‘๐Ÿ‘
@@ -0,0 +1,32 @@ +import React, { createContext, useState, useCallback, ReactNode } from 'react'; +import ErrorToast from '../components/ErrorToast/ErrorToast'; + +export interface ToastContextType { + showToast: (message: string) => void; +} + +export const ToastContext = createContext<ToastContextType | undefined>(undefined); + +interface ToastProviderProps { + children: ReactNode; +} + +export const ToastProvider: React.FC<ToastProviderProps> = ({ children }) => { + const [isOpen, setIsOpen] = useState(false); + const [message, setMessage] = useState(''); + + const showToast = useCallback((message: string) => { + setMessage(message); + setIsOpen(true); + setTimeout(() => { + setIsOpen(false); + }, 3000); + }, []); + + return ( + <ToastContext.Provider value={{ showToast }}> + {children} + {isOpen && <ErrorToast message={message} />} + </ToastContext.Provider> + ); +};
Unknown
๋ณ„๋„์˜ Provider๋กœ ๋งŒ๋“ค์–ด ์ค€ ๊ฒƒ ๋„ˆ๋ฌด ์ข‹๋„ค์š”
@@ -0,0 +1,95 @@ +import { CartItemType, ProductType } from '../types'; +import { generateBasicToken } from './auth'; + +const API_URL = import.meta.env.VITE_API_URL; +const USER_ID = import.meta.env.VITE_USER_ID; +const USER_PASSWORD = import.meta.env.VITE_USER_PASSWORD; + +/** + * ๊ณตํ†ต ์š”์ฒญ์„ ์ฒ˜๋ฆฌํ•˜๋Š” ํ•จ์ˆ˜ + * @param {string} endpoint - API endpoint + * @param {RequestInit} options - fetch options + * @returns {Response} - fetch response + */ +async function makeRequest(endpoint: string, options: RequestInit): Promise<Response> { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + + const response = await fetch(`${API_URL}${endpoint}`, { + ...options, + headers: { + ...options.headers, + Authorization: token, + 'Content-Type': 'application/json', + }, + }); + + if (!response.ok) { + throw new Error(`Failed to ${options.method?.toLowerCase()} ${endpoint}`); + } + + return response; +} + +interface FetchProductsParams { + category?: string; + page?: number; + size?: number; + sort?: string; +} + +/** + * fetchCartItems - API์—์„œ ์ƒํ’ˆ ๋ชฉ๋ก์„ fetchํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<ProductType[]>} + */ +export async function fetchProducts(params: FetchProductsParams = {}): Promise<ProductType[]> { + const queryString = Object.entries(params) + .map(([key, value]) => { + if (key === 'category' && value === 'all') { + return; + } else { + return `${key}=${value}`; + } + }) + .join('&'); + const response = await makeRequest(`/products?${queryString}`, { + method: 'GET', + }); + const data = await response.json(); + + return data.content; +} + +/** + * addCartItem - ์„ ํƒํ•œ ์ƒํ’ˆ์„ ์žฅ๋ฐ”๊ตฌ๋‹ˆ์— ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<void>} + */ +export async function addCartItem(productId: number): Promise<void> { + await makeRequest('/cart-items', { + method: 'POST', + body: JSON.stringify({ productId }), + }); +} + +/** + * fetchCartItem - API์—์„œ ์žฅ๋ฐ”๊ตฌ๋‹ˆ ๋ชฉ๋ก์„ fetchํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<CartItemType[]>} + */ +export async function fetchCartItem(): Promise<CartItemType[]> { + const response = await makeRequest('/cart-items?page=0&size=100', { + method: 'GET', + }); + + const data = await response.json(); + + return data.content; +} + +/** + * deleteCartItem - ์„ ํƒํ•œ ์ƒํ’ˆ์„ ์žฅ๋ฐ”๊ตฌ๋‹ˆ์—์„œ ์‚ญ์ œํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<void>} + */ +export async function deleteCartItem(cartItemId: number): Promise<void> { + await makeRequest(`/cart-items/${cartItemId}`, { + method: 'DELETE', + }); +}
TypeScript
๋งž์•„์š”... ์ž„์‹œ๋ฐฉํŽธ์ด์—ˆ๋Š”๋ฐ ๊ทธ๋ƒฅ ๊นŒ๋จน๊ณ  ๋„˜์–ด๊ฐ”๋„ค์š” ใ…œใ…œ
@@ -0,0 +1,95 @@ +import { CartItemType, ProductType } from '../types'; +import { generateBasicToken } from './auth'; + +const API_URL = import.meta.env.VITE_API_URL; +const USER_ID = import.meta.env.VITE_USER_ID; +const USER_PASSWORD = import.meta.env.VITE_USER_PASSWORD; + +/** + * ๊ณตํ†ต ์š”์ฒญ์„ ์ฒ˜๋ฆฌํ•˜๋Š” ํ•จ์ˆ˜ + * @param {string} endpoint - API endpoint + * @param {RequestInit} options - fetch options + * @returns {Response} - fetch response + */ +async function makeRequest(endpoint: string, options: RequestInit): Promise<Response> { + const token = generateBasicToken(USER_ID, USER_PASSWORD); + + const response = await fetch(`${API_URL}${endpoint}`, { + ...options, + headers: { + ...options.headers, + Authorization: token, + 'Content-Type': 'application/json', + }, + }); + + if (!response.ok) { + throw new Error(`Failed to ${options.method?.toLowerCase()} ${endpoint}`); + } + + return response; +} + +interface FetchProductsParams { + category?: string; + page?: number; + size?: number; + sort?: string; +} + +/** + * fetchCartItems - API์—์„œ ์ƒํ’ˆ ๋ชฉ๋ก์„ fetchํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<ProductType[]>} + */ +export async function fetchProducts(params: FetchProductsParams = {}): Promise<ProductType[]> { + const queryString = Object.entries(params) + .map(([key, value]) => { + if (key === 'category' && value === 'all') { + return; + } else { + return `${key}=${value}`; + } + }) + .join('&'); + const response = await makeRequest(`/products?${queryString}`, { + method: 'GET', + }); + const data = await response.json(); + + return data.content; +} + +/** + * addCartItem - ์„ ํƒํ•œ ์ƒํ’ˆ์„ ์žฅ๋ฐ”๊ตฌ๋‹ˆ์— ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<void>} + */ +export async function addCartItem(productId: number): Promise<void> { + await makeRequest('/cart-items', { + method: 'POST', + body: JSON.stringify({ productId }), + }); +} + +/** + * fetchCartItem - API์—์„œ ์žฅ๋ฐ”๊ตฌ๋‹ˆ ๋ชฉ๋ก์„ fetchํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<CartItemType[]>} + */ +export async function fetchCartItem(): Promise<CartItemType[]> { + const response = await makeRequest('/cart-items?page=0&size=100', { + method: 'GET', + }); + + const data = await response.json(); + + return data.content; +} + +/** + * deleteCartItem - ์„ ํƒํ•œ ์ƒํ’ˆ์„ ์žฅ๋ฐ”๊ตฌ๋‹ˆ์—์„œ ์‚ญ์ œํ•ฉ๋‹ˆ๋‹ค. + * @returns {Promise<void>} + */ +export async function deleteCartItem(cartItemId: number): Promise<void> { + await makeRequest(`/cart-items/${cartItemId}`, { + method: 'DELETE', + }); +}
TypeScript
๊ทธ๋Ÿฐ๋ฐ.. ์ด๋ฒˆ ์žฅ๋ฐ”๊ตฌ๋‹ˆ api๋Š” 20๊ฐœ๋งŒ ๋‹ด์„ ์ˆ˜ ์žˆ๊ฒŒ ๋งŒ๋“ค์–ด์ ธ์žˆ๋”๋ผ๊ตฌ์š”.. ์ง€๊ธˆ api ๊ตฌํ˜„์‚ฌํ•ญ์— ๋งž์ถœ์ง€, ์•„๋‹ˆ๋ฉด ๋ฏธ๋ž˜์˜ ๋ณ€๊ฒฝ์—๋„ ์šฉ์ดํ•˜๊ฒŒ ์ฝ”๋“œ๋ฅผ ๋ฐ”๊ฟ€์ง€๋Š” ์ƒ๊ฐํ•ด ๋ด์•ผํ•  ๋ฌธ์ œ์ธ ๊ฒƒ ๊ฐ™์•„์š”. ์ด ๋ถ€๋ถ„์„ ๋ฐ”๊ฟ”์•ผ ํ•œ๋‹ค๋ฉด ์œ„์˜ >if (key === 'category' && value === 'all') ์ด ์ฝ”๋“œ์—์„œ๋„ default๋กœ ๋“ค์–ด๊ฐˆ ์ˆ˜ ์žˆ๋Š” sort=id,asc๋„ ์ƒ๊ฐํ•ด๋ด์•ผ ํ•  ๊ฒƒ ๊ฐ™๊ณ ์š”
@@ -0,0 +1,21 @@ +import { SelectHTMLAttributes, PropsWithChildren } from 'react'; +import styles from './Select.module.css'; + +interface Props extends PropsWithChildren<SelectHTMLAttributes<HTMLSelectElement>> { + options: Record<string, string>; +} + +const Select = ({ options, defaultValue, children, ...props }: Props) => { + return ( + <select {...props} className={styles.selectContainer} defaultValue={defaultValue}> + {children} + {Object.keys(options).map((option) => ( + <option key={option} value={option}> + {options[option]} + </option> + ))} + </select> + ); +}; + +export default Select;
Unknown
entries๋ผ๋Š” ํ•จ์ˆ˜๋„ ์žˆ์œผ๋‹ˆ ์ฐพ์•„๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”..! ``` js Object.entries(options).map([optionEn,optionKo])=>{ ... } ```
@@ -0,0 +1,44 @@ +package christmas.controller; + +import christmas.domain.event.EventCalculator; +import christmas.domain.date.ReservationDate; +import christmas.domain.order.OrderMenuParser; +import christmas.view.InputView; +import christmas.view.OutputView; + +public class ChristmasController { + public void run(){ + OutputView.printStart(); + ReservationDate reservationDate = reservationDate(); + OrderMenuParser orderMenu = orderMenu(); + OutputView.printDate(reservationDate); + OutputView.printOrderMenu(orderMenu); + OutputView.printTotalPrice(orderMenu); + EventCalculator eventCalculator = new EventCalculator(reservationDate, orderMenu); + OutputView.printGiftMenu(orderMenu); + OutputView.printEvent(eventCalculator); + OutputView.printTotalDiscount(eventCalculator); + OutputView.printExpectedDiscount(eventCalculator); + OutputView.printEventBadge(eventCalculator); + } + + private ReservationDate reservationDate() { + while (true) { + try { + return new ReservationDate(InputView.readDate()); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private OrderMenuParser orderMenu(){ + while (true) { + try { + return new OrderMenuParser(InputView.readMenu()); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } +}
Java
ํ•œ ๋ฉ”์„œ๋“œ์—์„œ ๋„ˆ๋ฌด ๋ณต์žกํ•ด ๋ณด์ด๋„ค์š” ๋ฉ”์„œ๋“œ๋ฅผ ๋ถ„๋ฆฌํ•˜๋ฉด ๋” ์ข‹์„๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,22 @@ +package christmas.domain.event; + +import christmas.constant.ChristmasConfig; + +public class ChristmasEvent { + private final int reservationDate; + + public ChristmasEvent(int reservationDate) { + this.reservationDate = reservationDate; + } + + public int calculateDiscount() { + if (isChristmasPeriod()) { + return ChristmasConfig.DISCOUNT_MONEY + ChristmasConfig.INCREASE_MONEY * (reservationDate - ChristmasConfig.START_DAY); + } + return ChristmasConfig.ZERO; + } + + private boolean isChristmasPeriod() { + return reservationDate >= ChristmasConfig.START_DAY && reservationDate <= ChristmasConfig.END_DAY; + } +} \ No newline at end of file
Java
๊ฐ ์ด๋ฒคํŠธ ํด๋ž˜์Šค์—์„œ ๋‚ ์งœ๋ฅผ ๊ฒ€์ฆํ•˜๋Š” ๊ฒƒ๋„ ์ข‹์€๋ฐ ๊ฐ๊ฐ์˜ ์ด๋ฒคํŠธ ๊ธฐ๊ฐ„์— ํฌํ•จ๋˜๋Š”์ง€ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ถ€๋ถ„์„ ReservationDate ํด๋ž˜์Šค์—์„œ ์ฒ˜๋ฆฌํ•ด๋„ ์ข‹์„๊ฑฐ ๊ฐ™์•„์š”!
@@ -2,15 +2,18 @@ import jakarta.servlet.http.HttpServletRequest; import java.util.ArrayList; +import java.util.stream.Collectors; import nextstep.app.domain.Member; import nextstep.app.domain.MemberRepository; +import nextstep.security.access.NullRoleHierarchy; +import nextstep.security.access.RoleHierarchy; +import nextstep.security.access.RoleHierarchyImpl; import nextstep.security.authentication.AuthenticationException; import nextstep.security.authentication.BasicAuthenticationFilter; import nextstep.security.authentication.UsernamePasswordAuthenticationFilter; import nextstep.security.authorization.AuthorizationFilter; import nextstep.security.authorization.AuthorizationManager; import nextstep.security.authorization.SecuredMethodInterceptor; -import nextstep.security.authorization.method.SecuredAuthorizationManager; import nextstep.security.authorization.web.AuthenticatedAuthorizationManager; import nextstep.security.authorization.web.AuthorityAuthorizationManager; import nextstep.security.authorization.web.DenyAllAuthorizationManager; @@ -20,13 +23,14 @@ import nextstep.security.config.FilterChainProxy; import nextstep.security.config.SecurityFilterChain; import nextstep.security.context.SecurityContextHolderFilter; +import nextstep.security.core.GrantedAuthority; +import nextstep.security.core.SimpleGrantedAuthority; import nextstep.security.userdetails.UserDetails; import nextstep.security.userdetails.UserDetailsService; import nextstep.security.util.AnyRequestMatcher; import nextstep.security.util.MvcRequestMatcher; import nextstep.security.util.RequestMatcherEntry; import nextstep.security.authorization.web.PermitAllAuthorizationManager; -import org.aopalliance.intercept.MethodInvocation; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; @@ -57,19 +61,22 @@ public FilterChainProxy filterChainProxy(List<SecurityFilterChain> securityFilte @Bean public SecuredMethodInterceptor securedMethodInterceptor() { - return new SecuredMethodInterceptor(securedAuthorizationManager()); + return new SecuredMethodInterceptor(new AuthorityAuthorizationManager<>(roleHierarchy())); } @Bean - public AuthorizationManager<MethodInvocation> securedAuthorizationManager() { - return new SecuredAuthorizationManager(); + public RoleHierarchy roleHierarchy() { + return RoleHierarchyImpl.with() + .role("ADMIN").implies("USER") + .role("USER").implies("GUEST") + .build(); } @Bean public AuthorizationManager<HttpServletRequest> requestAuthorizationManager() { List<RequestMatcherEntry<AuthorizationManager>> mappings = new ArrayList<>(); mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/members"), - new AuthorityAuthorizationManager<HttpServletRequest>(Set.of("ADMIN")))); + new AuthorityAuthorizationManager(new NullRoleHierarchy(), Set.of("ADMIN")))); mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/members/me"), new AuthenticatedAuthorizationManager())); mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/search"), @@ -108,8 +115,8 @@ public String getPassword() { } @Override - public Set<String> getAuthorities() { - return member.getRoles(); + public Set<GrantedAuthority> getAuthorities() { + return member.getRoles().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet()); } }; };
Java
์ž˜ ์ถ”๊ฐ€ํ•ด์ฃผ์…จ๋„ค์š” ๐Ÿ‘
@@ -0,0 +1,13 @@ +package nextstep.security.access; + +import java.util.Collection; +import nextstep.security.core.GrantedAuthority; + +public final class NullRoleHierarchy implements RoleHierarchy { + + @Override + public Collection<GrantedAuthority> getReachableGrantedAuthorities( + Collection<GrantedAuthority> authorities) { + return authorities; + } +}
Java
`<? extends GrantedAuthority>`๋กœ ์ง€์ •๋˜์–ด์žˆ์„ ์ด์œ ๊ฐ€ ์–ด๋–ป๊ฒŒ ๋ ๊นŒ์š”?
@@ -4,19 +4,22 @@ import java.util.Collection; import java.util.Collections; import java.util.Set; +import nextstep.security.access.RoleHierarchy; import nextstep.security.authentication.Authentication; import nextstep.security.authorization.AuthorizationDecision; import nextstep.security.authorization.AuthorizationManager; import nextstep.security.authorization.Secured; import nextstep.security.authorization.web.AuthorityAuthorizationManager; +import nextstep.security.core.GrantedAuthority; import org.aopalliance.intercept.MethodInvocation; public class SecuredAuthorizationManager implements AuthorizationManager<MethodInvocation> { - private AuthorityAuthorizationManager<Collection<String>> authorityAuthorizationManager; + private final AuthorityAuthorizationManager<Collection<String>> authorityAuthorizationManager; - public void setAuthorityAuthorizationManager(Collection<String> authorities) { - authorityAuthorizationManager = new AuthorityAuthorizationManager<>(authorities); + public SecuredAuthorizationManager( + AuthorityAuthorizationManager<Collection<String>> authorityAuthorizationManager) { + this.authorityAuthorizationManager = authorityAuthorizationManager; } @Override @@ -26,8 +29,8 @@ public AuthorizationDecision check(Authentication authentication, MethodInvocati if (authorities.isEmpty()) { return null; } - setAuthorityAuthorizationManager(authorities); - return authorities.isEmpty() ? null : authorityAuthorizationManager.check(authentication, authorities); + + return authorityAuthorizationManager.check(authentication, authorities); } private Collection<String> getAuthorities(MethodInvocation invocation) {
Java
`RoleHierarchy`๋ฅผ ๋”ฐ๋กœ ๋‘˜ ํ•„์š”๊ฐ€ ์—†์„ ๊ฒƒ ๊ฐ™์•„์š”. `authorityAuthorizationManager`์—์„œ ์ฒ˜๋ฆฌํ•˜๊ฒŒ ๋‘๋ฉด ๋ ํ…๋ฐ `SecuredAuthorizationManager`๊ฐ€ ๊ฐ€์งˆ ํ•„์š”๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -1,38 +1,53 @@ package nextstep.security.authorization.web; import java.util.Collection; +import java.util.Set; +import nextstep.security.access.RoleHierarchy; import nextstep.security.authentication.Authentication; import nextstep.security.authentication.AuthenticationException; import nextstep.security.authorization.AuthorizationDecision; import nextstep.security.authorization.AuthorizationManager; +import nextstep.security.core.GrantedAuthority; public class AuthorityAuthorizationManager<T> implements AuthorizationManager<T> { + private final RoleHierarchy roleHierarchy; + private Collection<String> authorities; - private final Collection<String> authorities; + public AuthorityAuthorizationManager(RoleHierarchy roleHierarchy) { + this.roleHierarchy = roleHierarchy; + this.authorities = Set.of(); + } - public AuthorityAuthorizationManager(Collection<String> authorities) { + public AuthorityAuthorizationManager(RoleHierarchy roleHierarchy, Collection<String> authorities) { + this.roleHierarchy = roleHierarchy; this.authorities = authorities; } - @Override public AuthorizationDecision check(Authentication authentication, T object) { if (authentication == null) { throw new AuthenticationException(); } + if(object instanceof Collection<?>) { + this.authorities = (Collection<String>) object; + } + boolean hasAuthority = isAuthorized(authentication, authorities); return AuthorizationDecision.of(hasAuthority); } - private boolean isAuthorized(Authentication authentication, Collection<String> authorities) { - for (String authority : authentication.getAuthorities()) { - if (authorities.contains(authority)) { + for (GrantedAuthority grantedAuthority : getGrantedAuthorities(authentication)) { + if (authorities.contains(grantedAuthority.getAuthority())) { return true; } } return false; } + + private Collection<GrantedAuthority> getGrantedAuthorities(Authentication authentication) { + return this.roleHierarchy.getReachableGrantedAuthorities(authentication.getAuthorities()); + } }
Java
```suggestion private final RoleHierarchy roleHierarchy = new NullRoleHierarchy(); ``` ๋ถˆ๋ณ€์ด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™๋„ค์š” :)
@@ -1,38 +1,53 @@ package nextstep.security.authorization.web; import java.util.Collection; +import java.util.Set; +import nextstep.security.access.RoleHierarchy; import nextstep.security.authentication.Authentication; import nextstep.security.authentication.AuthenticationException; import nextstep.security.authorization.AuthorizationDecision; import nextstep.security.authorization.AuthorizationManager; +import nextstep.security.core.GrantedAuthority; public class AuthorityAuthorizationManager<T> implements AuthorizationManager<T> { + private final RoleHierarchy roleHierarchy; + private Collection<String> authorities; - private final Collection<String> authorities; + public AuthorityAuthorizationManager(RoleHierarchy roleHierarchy) { + this.roleHierarchy = roleHierarchy; + this.authorities = Set.of(); + } - public AuthorityAuthorizationManager(Collection<String> authorities) { + public AuthorityAuthorizationManager(RoleHierarchy roleHierarchy, Collection<String> authorities) { + this.roleHierarchy = roleHierarchy; this.authorities = authorities; } - @Override public AuthorizationDecision check(Authentication authentication, T object) { if (authentication == null) { throw new AuthenticationException(); } + if(object instanceof Collection<?>) { + this.authorities = (Collection<String>) object; + } + boolean hasAuthority = isAuthorized(authentication, authorities); return AuthorizationDecision.of(hasAuthority); } - private boolean isAuthorized(Authentication authentication, Collection<String> authorities) { - for (String authority : authentication.getAuthorities()) { - if (authorities.contains(authority)) { + for (GrantedAuthority grantedAuthority : getGrantedAuthorities(authentication)) { + if (authorities.contains(grantedAuthority.getAuthority())) { return true; } } return false; } + + private Collection<GrantedAuthority> getGrantedAuthorities(Authentication authentication) { + return this.roleHierarchy.getReachableGrantedAuthorities(authentication.getAuthorities()); + } }
Java
๊ธฐ๋Šฅ์œผ๋กœ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ์ถœ๋ ฅ๋ฌธ์ธ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,122 @@ +package nextstep.security.access; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import nextstep.security.core.GrantedAuthority; +import nextstep.security.core.SimpleGrantedAuthority; + +public class RoleHierarchyImpl implements RoleHierarchy { + + private final Map<String, Set<GrantedAuthority>> rolesReachableInOneOrMoreStepsMap; + + private RoleHierarchyImpl(Map<String, Set<GrantedAuthority>> hierarchy) { + this.rolesReachableInOneOrMoreStepsMap = buildRolesReachableInOneOrMoreStepsMap(hierarchy); + } + + public static Builder with() { + return new Builder(); + } + + @Override + public Collection<GrantedAuthority> getReachableGrantedAuthorities( + Collection<GrantedAuthority> authorities) { + if (authorities == null || authorities.isEmpty()) { + return Collections.emptyList(); + } + + Set<GrantedAuthority> reachableRoles = new HashSet<>(); + Set<String> processedNames = new HashSet<>(); + + for (GrantedAuthority authority : authorities) { + if (authority.getAuthority() == null) { + reachableRoles.add(authority); + continue; + } + + if (!processedNames.add(authority.getAuthority())) { + continue; + } + + reachableRoles.add(authority); + + Set<GrantedAuthority> lowerRoles = this.rolesReachableInOneOrMoreStepsMap.get(authority.getAuthority()); + if (lowerRoles == null) { + continue; + } + for (GrantedAuthority role : lowerRoles) { + if (processedNames.add(role.getAuthority())) { + reachableRoles.add(role); + } + } + } + + return new ArrayList<>(reachableRoles); + } + + private static Map<String, Set<GrantedAuthority>> buildRolesReachableInOneOrMoreStepsMap( + Map<String, Set<GrantedAuthority>> hierarchy) { + Map<String, Set<GrantedAuthority>> rolesReachableInOneOrMoreStepsMap = new HashMap<>(); + for (String roleName : hierarchy.keySet()) { + Set<GrantedAuthority> rolesToVisitSet = new HashSet<>(hierarchy.get(roleName)); + Set<GrantedAuthority> visitedRolesSet = new HashSet<>(); + while (!rolesToVisitSet.isEmpty()) { + GrantedAuthority lowerRole = rolesToVisitSet.iterator().next(); + rolesToVisitSet.remove(lowerRole); + if (!visitedRolesSet.add(lowerRole) || !hierarchy.containsKey(lowerRole.getAuthority())) { + continue; + } + if (roleName.equals(lowerRole.getAuthority())) { + throw new CycleInRoleHierarchyException(); + } + rolesToVisitSet.addAll(hierarchy.get(lowerRole.getAuthority())); + } + rolesReachableInOneOrMoreStepsMap.put(roleName, visitedRolesSet); + } + return rolesReachableInOneOrMoreStepsMap; + } + + public static final class Builder { + + private final Map<String, Set<GrantedAuthority>> hierarchy; + + private Builder() { + this.hierarchy = new LinkedHashMap<>(); + } + + public ImpliedRoles role(String role) { + return new ImpliedRoles(role); + } + + public RoleHierarchyImpl build() { + return new RoleHierarchyImpl(this.hierarchy); + } + + private Builder addHierarchy(String role, String... impliedRoles) { + Set<GrantedAuthority> withPrefix = this.hierarchy.computeIfAbsent(role + , (r) -> new HashSet<>()); + for (String impliedRole : impliedRoles) { + withPrefix.add(new SimpleGrantedAuthority(impliedRole)); + } + return this; + } + + public final class ImpliedRoles { + + private final String role; + + private ImpliedRoles(String role) { + this.role = role; + } + + public Builder implies(String... impliedRoles) { + return Builder.this.addHierarchy(this.role, impliedRoles); + } + } + } +}
Java
์ž˜ ์„ค๊ณ„ํ•ด์ฃผ์‹  ํด๋ž˜์Šค์— ๊ธฐ๋Šฅ ๋ช…์„ธ๋ฅผ ํ…Œ์ŠคํŠธ๋กœ ํ•œ๋ฒˆ ์งœ๋ณด๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”? ํ…Œ์ŠคํŠธ๊ฐ€ ์‹คํŒจ ์ผ€์ด์Šค๋ฅผ ๋ณดํ˜ธํ•ด์ฃผ๊ธฐ๋„ ํ•˜์ง€๋งŒ ๊ธฐ๋Šฅ์„ ํ‘œํ˜„ํ•ด์ฃผ๋Š” ๋ช…์„ธ์„œ๊ฐ€ ๋  ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,122 @@ +package nextstep.security.access; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import nextstep.security.core.GrantedAuthority; +import nextstep.security.core.SimpleGrantedAuthority; + +public class RoleHierarchyImpl implements RoleHierarchy { + + private final Map<String, Set<GrantedAuthority>> rolesReachableInOneOrMoreStepsMap; + + private RoleHierarchyImpl(Map<String, Set<GrantedAuthority>> hierarchy) { + this.rolesReachableInOneOrMoreStepsMap = buildRolesReachableInOneOrMoreStepsMap(hierarchy); + } + + public static Builder with() { + return new Builder(); + } + + @Override + public Collection<GrantedAuthority> getReachableGrantedAuthorities( + Collection<GrantedAuthority> authorities) { + if (authorities == null || authorities.isEmpty()) { + return Collections.emptyList(); + } + + Set<GrantedAuthority> reachableRoles = new HashSet<>(); + Set<String> processedNames = new HashSet<>(); + + for (GrantedAuthority authority : authorities) { + if (authority.getAuthority() == null) { + reachableRoles.add(authority); + continue; + } + + if (!processedNames.add(authority.getAuthority())) { + continue; + } + + reachableRoles.add(authority); + + Set<GrantedAuthority> lowerRoles = this.rolesReachableInOneOrMoreStepsMap.get(authority.getAuthority()); + if (lowerRoles == null) { + continue; + } + for (GrantedAuthority role : lowerRoles) { + if (processedNames.add(role.getAuthority())) { + reachableRoles.add(role); + } + } + } + + return new ArrayList<>(reachableRoles); + } + + private static Map<String, Set<GrantedAuthority>> buildRolesReachableInOneOrMoreStepsMap( + Map<String, Set<GrantedAuthority>> hierarchy) { + Map<String, Set<GrantedAuthority>> rolesReachableInOneOrMoreStepsMap = new HashMap<>(); + for (String roleName : hierarchy.keySet()) { + Set<GrantedAuthority> rolesToVisitSet = new HashSet<>(hierarchy.get(roleName)); + Set<GrantedAuthority> visitedRolesSet = new HashSet<>(); + while (!rolesToVisitSet.isEmpty()) { + GrantedAuthority lowerRole = rolesToVisitSet.iterator().next(); + rolesToVisitSet.remove(lowerRole); + if (!visitedRolesSet.add(lowerRole) || !hierarchy.containsKey(lowerRole.getAuthority())) { + continue; + } + if (roleName.equals(lowerRole.getAuthority())) { + throw new CycleInRoleHierarchyException(); + } + rolesToVisitSet.addAll(hierarchy.get(lowerRole.getAuthority())); + } + rolesReachableInOneOrMoreStepsMap.put(roleName, visitedRolesSet); + } + return rolesReachableInOneOrMoreStepsMap; + } + + public static final class Builder { + + private final Map<String, Set<GrantedAuthority>> hierarchy; + + private Builder() { + this.hierarchy = new LinkedHashMap<>(); + } + + public ImpliedRoles role(String role) { + return new ImpliedRoles(role); + } + + public RoleHierarchyImpl build() { + return new RoleHierarchyImpl(this.hierarchy); + } + + private Builder addHierarchy(String role, String... impliedRoles) { + Set<GrantedAuthority> withPrefix = this.hierarchy.computeIfAbsent(role + , (r) -> new HashSet<>()); + for (String impliedRole : impliedRoles) { + withPrefix.add(new SimpleGrantedAuthority(impliedRole)); + } + return this; + } + + public final class ImpliedRoles { + + private final String role; + + private ImpliedRoles(String role) { + this.role = role; + } + + public Builder implies(String... impliedRoles) { + return Builder.this.addHierarchy(this.role, impliedRoles); + } + } + } +}
Java
```suggestion private final Map<String, Set<GrantedAuthority>> rolesReachableInOneOrMoreStepsMap; ``` ์—ฌ๊ธฐ๋„ ์ด๋ ‡๊ฒŒ ์ˆ˜์ •ํ•  ์ˆ˜ ์žˆ๊ฒ ๋„ค์š”~
@@ -0,0 +1,122 @@ +package nextstep.security.access; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import nextstep.security.core.GrantedAuthority; +import nextstep.security.core.SimpleGrantedAuthority; + +public class RoleHierarchyImpl implements RoleHierarchy { + + private final Map<String, Set<GrantedAuthority>> rolesReachableInOneOrMoreStepsMap; + + private RoleHierarchyImpl(Map<String, Set<GrantedAuthority>> hierarchy) { + this.rolesReachableInOneOrMoreStepsMap = buildRolesReachableInOneOrMoreStepsMap(hierarchy); + } + + public static Builder with() { + return new Builder(); + } + + @Override + public Collection<GrantedAuthority> getReachableGrantedAuthorities( + Collection<GrantedAuthority> authorities) { + if (authorities == null || authorities.isEmpty()) { + return Collections.emptyList(); + } + + Set<GrantedAuthority> reachableRoles = new HashSet<>(); + Set<String> processedNames = new HashSet<>(); + + for (GrantedAuthority authority : authorities) { + if (authority.getAuthority() == null) { + reachableRoles.add(authority); + continue; + } + + if (!processedNames.add(authority.getAuthority())) { + continue; + } + + reachableRoles.add(authority); + + Set<GrantedAuthority> lowerRoles = this.rolesReachableInOneOrMoreStepsMap.get(authority.getAuthority()); + if (lowerRoles == null) { + continue; + } + for (GrantedAuthority role : lowerRoles) { + if (processedNames.add(role.getAuthority())) { + reachableRoles.add(role); + } + } + } + + return new ArrayList<>(reachableRoles); + } + + private static Map<String, Set<GrantedAuthority>> buildRolesReachableInOneOrMoreStepsMap( + Map<String, Set<GrantedAuthority>> hierarchy) { + Map<String, Set<GrantedAuthority>> rolesReachableInOneOrMoreStepsMap = new HashMap<>(); + for (String roleName : hierarchy.keySet()) { + Set<GrantedAuthority> rolesToVisitSet = new HashSet<>(hierarchy.get(roleName)); + Set<GrantedAuthority> visitedRolesSet = new HashSet<>(); + while (!rolesToVisitSet.isEmpty()) { + GrantedAuthority lowerRole = rolesToVisitSet.iterator().next(); + rolesToVisitSet.remove(lowerRole); + if (!visitedRolesSet.add(lowerRole) || !hierarchy.containsKey(lowerRole.getAuthority())) { + continue; + } + if (roleName.equals(lowerRole.getAuthority())) { + throw new CycleInRoleHierarchyException(); + } + rolesToVisitSet.addAll(hierarchy.get(lowerRole.getAuthority())); + } + rolesReachableInOneOrMoreStepsMap.put(roleName, visitedRolesSet); + } + return rolesReachableInOneOrMoreStepsMap; + } + + public static final class Builder { + + private final Map<String, Set<GrantedAuthority>> hierarchy; + + private Builder() { + this.hierarchy = new LinkedHashMap<>(); + } + + public ImpliedRoles role(String role) { + return new ImpliedRoles(role); + } + + public RoleHierarchyImpl build() { + return new RoleHierarchyImpl(this.hierarchy); + } + + private Builder addHierarchy(String role, String... impliedRoles) { + Set<GrantedAuthority> withPrefix = this.hierarchy.computeIfAbsent(role + , (r) -> new HashSet<>()); + for (String impliedRole : impliedRoles) { + withPrefix.add(new SimpleGrantedAuthority(impliedRole)); + } + return this; + } + + public final class ImpliedRoles { + + private final String role; + + private ImpliedRoles(String role) { + this.role = role; + } + + public Builder implies(String... impliedRoles) { + return Builder.this.addHierarchy(this.role, impliedRoles); + } + } + } +}
Java
```suggestion } if (roleName.equals(lowerRole.getAuthority())) { throw new RuntimeException(); } ``` else if๊ฐ€ ๊ฐ€๋…์„ฑ์ด ๋†’๋‹ค๋Š” ์˜๊ฒฌ์ด ์žˆ์„ ์ˆ˜ ์žˆ์ง€๋งŒ ๊ฐœ์ธ์ ์œผ๋กœ๋Š” if ํ›„์˜ else, else if๋Š” ์ปจํ…์ŠคํŠธ๋ฅผ ๊ณ„์† ๋“ค๊ณ  ์ฝ”๋“œ๋ฅผ ์ฝ๊ฒŒ ๋งŒ๋“œ๋Š” ์›์ธ์ด๋ผ ๊ทธ๋ƒฅ if ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ๋” ๋‚ซ๋‹ค๋Š” ์ƒ๊ฐ์ž…๋‹ˆ๋‹ค.
@@ -0,0 +1,13 @@ +package nextstep.security.access; + +import java.util.Collection; +import nextstep.security.core.GrantedAuthority; + +public final class NullRoleHierarchy implements RoleHierarchy { + + @Override + public Collection<GrantedAuthority> getReachableGrantedAuthorities( + Collection<GrantedAuthority> authorities) { + return authorities; + } +}
Java
๊ธฐ์กด ์Šคํ”„๋ง์‹œํ๋ฆฌํ‹ฐ ์ฝ”๋“œ์—์„œ ๊ฐ€์ ธ์˜จ ๋ถ€๋ถ„์ธ๋ฐ, ์ƒ๊ฐํ•ด๋ณด๋‹ˆ ์ €ํฌ ๊ตฌ์กฐ์—์„  ๋ถˆํ•„์š”ํ•˜๋„ค์š”,, ์ˆ˜์ •ํ•ด๋‘๊ฒ ์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,93 @@ +package nextstep.security.access; + +import nextstep.security.core.GrantedAuthority; +import nextstep.security.core.SimpleGrantedAuthority; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.Collection; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class RoleHierarchyTest { + + @Test + @DisplayName("์—ญํ•  ๊ณ„์ธต์ด ์—†์„ ๋•Œ ์ž…๋ ฅ๋œ ๊ถŒํ•œ๋งŒ ๋ฐ˜ํ™˜ ํ•œ๋‹ค.") + void getReachableGrantedAuthorities_NoHierarchy() { + // Given + RoleHierarchy roleHierarchy = new NullRoleHierarchy(); + Collection<GrantedAuthority> authorities = Set.of(new SimpleGrantedAuthority("USER")); + + // When + Collection<GrantedAuthority> reachableAuthorities = roleHierarchy.getReachableGrantedAuthorities(authorities); + + // Then + assertThat(reachableAuthorities).hasSize(1); + assertThat(reachableAuthorities).contains(new SimpleGrantedAuthority("USER")); + } + + @Test + @DisplayName("์—ญํ•  ๊ณ„์ธต์ด ์กด์žฌ ์‹œ ๋ชจ๋“  ํ•˜์œ„ ๊ถŒํ•œ ๋ฐ˜ํ™˜ ํ•œ๋‹ค.") + void getReachableGrantedAuthorities_WithHierarchy() { + // Given + RoleHierarchy roleHierarchy = RoleHierarchyImpl.with() + .role("ADMIN").implies("USER") + .role("USER").implies("GUEST") + .build(); + Collection<GrantedAuthority> authorities = Set.of(new SimpleGrantedAuthority("ADMIN")); + + // When + Collection<GrantedAuthority> reachableAuthorities = roleHierarchy.getReachableGrantedAuthorities(authorities); + + // Then + assertThat(reachableAuthorities).hasSize(3); + assertThat(reachableAuthorities).containsExactlyInAnyOrder( + new SimpleGrantedAuthority("ADMIN"), + new SimpleGrantedAuthority("USER"), + new SimpleGrantedAuthority("GUEST") + ); + } + + @Test + @DisplayName("๊ณ„์ธต ๊ฐ„ ์ˆœํ™˜ ์ฐธ์กฐ ๋ฐœ์ƒ ์‹œ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.") + void shouldThrowExceptionForCircularRoleReferences() { + assertThatThrownBy(() -> RoleHierarchyImpl.with() + .role("ADMIN").implies("USER") + .role("USER").implies("GUEST") + .role("GUEST").implies("USER") + .build()) + .isInstanceOf(CycleInRoleHierarchyException.class); + } + + @Test + @DisplayName("๋นˆ ๊ถŒํ•œ ๋ฆฌ์ŠคํŠธ ์ž…๋ ฅ ์‹œ ๋นˆ ๊ฒฐ๊ณผ ๋ฐ˜ํ™˜") + void getReachableGrantedAuthorities_EmptyInput() { + // Given + RoleHierarchy roleHierarchy = RoleHierarchyImpl.with() + .role("ADMIN").implies("USER") + .role("USER").implies("GUEST") + .build(); + // When + Collection<GrantedAuthority> reachableAuthorities = roleHierarchy.getReachableGrantedAuthorities(Set.of()); + + // Then + assertThat(reachableAuthorities).isEmpty(); + } + + @Test + @DisplayName("Null ์ž…๋ ฅ ์‹œ ๋นˆ ๊ฒฐ๊ณผ ๋ฐ˜ํ™˜") + void getReachableGrantedAuthorities_NullInput() { + // Given + RoleHierarchy roleHierarchy = RoleHierarchyImpl.with() + .role("ADMIN").implies("USER") + .role("USER").implies("GUEST") + .build(); + // When + Collection<GrantedAuthority> reachableAuthorities = roleHierarchy.getReachableGrantedAuthorities(null); + + // Then + assertThat(reachableAuthorities).isEmpty(); + } +} \ No newline at end of file
Java
์ˆœํ™˜์ฐธ์กฐ ์˜ˆ์™ธ ํ…Œ์ŠคํŠธ๊นŒ์ง€ ์ž˜ ์ถ”๊ฐ€ํ•ด์ฃผ์…จ๋„ค์š” ๐Ÿ‘
@@ -0,0 +1,93 @@ +package nextstep.security.access; + +import nextstep.security.core.GrantedAuthority; +import nextstep.security.core.SimpleGrantedAuthority; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.Collection; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class RoleHierarchyTest { + + @Test + @DisplayName("์—ญํ•  ๊ณ„์ธต์ด ์—†์„ ๋•Œ ์ž…๋ ฅ๋œ ๊ถŒํ•œ๋งŒ ๋ฐ˜ํ™˜ ํ•œ๋‹ค.") + void getReachableGrantedAuthorities_NoHierarchy() { + // Given + RoleHierarchy roleHierarchy = new NullRoleHierarchy(); + Collection<GrantedAuthority> authorities = Set.of(new SimpleGrantedAuthority("USER")); + + // When + Collection<GrantedAuthority> reachableAuthorities = roleHierarchy.getReachableGrantedAuthorities(authorities); + + // Then + assertThat(reachableAuthorities).hasSize(1); + assertThat(reachableAuthorities).contains(new SimpleGrantedAuthority("USER")); + } + + @Test + @DisplayName("์—ญํ•  ๊ณ„์ธต์ด ์กด์žฌ ์‹œ ๋ชจ๋“  ํ•˜์œ„ ๊ถŒํ•œ ๋ฐ˜ํ™˜ ํ•œ๋‹ค.") + void getReachableGrantedAuthorities_WithHierarchy() { + // Given + RoleHierarchy roleHierarchy = RoleHierarchyImpl.with() + .role("ADMIN").implies("USER") + .role("USER").implies("GUEST") + .build(); + Collection<GrantedAuthority> authorities = Set.of(new SimpleGrantedAuthority("ADMIN")); + + // When + Collection<GrantedAuthority> reachableAuthorities = roleHierarchy.getReachableGrantedAuthorities(authorities); + + // Then + assertThat(reachableAuthorities).hasSize(3); + assertThat(reachableAuthorities).containsExactlyInAnyOrder( + new SimpleGrantedAuthority("ADMIN"), + new SimpleGrantedAuthority("USER"), + new SimpleGrantedAuthority("GUEST") + ); + } + + @Test + @DisplayName("๊ณ„์ธต ๊ฐ„ ์ˆœํ™˜ ์ฐธ์กฐ ๋ฐœ์ƒ ์‹œ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.") + void shouldThrowExceptionForCircularRoleReferences() { + assertThatThrownBy(() -> RoleHierarchyImpl.with() + .role("ADMIN").implies("USER") + .role("USER").implies("GUEST") + .role("GUEST").implies("USER") + .build()) + .isInstanceOf(CycleInRoleHierarchyException.class); + } + + @Test + @DisplayName("๋นˆ ๊ถŒํ•œ ๋ฆฌ์ŠคํŠธ ์ž…๋ ฅ ์‹œ ๋นˆ ๊ฒฐ๊ณผ ๋ฐ˜ํ™˜") + void getReachableGrantedAuthorities_EmptyInput() { + // Given + RoleHierarchy roleHierarchy = RoleHierarchyImpl.with() + .role("ADMIN").implies("USER") + .role("USER").implies("GUEST") + .build(); + // When + Collection<GrantedAuthority> reachableAuthorities = roleHierarchy.getReachableGrantedAuthorities(Set.of()); + + // Then + assertThat(reachableAuthorities).isEmpty(); + } + + @Test + @DisplayName("Null ์ž…๋ ฅ ์‹œ ๋นˆ ๊ฒฐ๊ณผ ๋ฐ˜ํ™˜") + void getReachableGrantedAuthorities_NullInput() { + // Given + RoleHierarchy roleHierarchy = RoleHierarchyImpl.with() + .role("ADMIN").implies("USER") + .role("USER").implies("GUEST") + .build(); + // When + Collection<GrantedAuthority> reachableAuthorities = roleHierarchy.getReachableGrantedAuthorities(null); + + // Then + assertThat(reachableAuthorities).isEmpty(); + } +} \ No newline at end of file
Java
ํ…Œ์ŠคํŠธ๊ฐ€ 27์—์„œ ์‹คํŒจํ•ด๋„ 28๋ผ์ธ์— ๋Œ€ํ•œ assertion๊นŒ์ง€ ํ”ผ๋“œ๋ฐฑ๋ฐ›์„ ์ˆ˜ ์žˆ๊ฒŒ `assertAll`๋ฅผ ํ™œ์šฉํ•ด ๋ณผ ์ˆ˜๋„ ์žˆ๊ฒ ๋„ค์š” :)
@@ -1,7 +1,14 @@ package christmas; +import christmas.controller.ChristmasController; +import christmas.exception.ExceptionHandler; +import christmas.exception.RetryExceptionHandler; + public class Application { public static void main(String[] args) { - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + ExceptionHandler handler = new RetryExceptionHandler(); + + ChristmasController controller = new ChristmasController(handler); + controller.service(); } }
Java
๋ฉ”์„œ๋“œ๋Š” ๋™์‚ฌ๋กœ ํ•˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค๊ณ  ์ƒ๊ฐํ•˜๋Š”๋ฐ, service() ๋Š” ์ •๋น„ํ•˜๋‹ค ๋ผ๋Š” ์˜๋ฏธ๋ผ๊ณ  ํ•ด์š”! ๋ฌผ๋ก , ์„œ๋น„์Šค ํ•˜๋‹ค~ ๋ผ๋Š” ๋А๋‚Œ์ธ ๊ฑด ์ดํ•ดํ•˜์ง€๋งŒ execute()๋‚˜ operate() ์™€ ๊ฐ™์€ ๋™์ž‘์„ ๊ฐ•์กฐํ•˜๋Š” ๋™์‚ฌ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฑด ์–ด๋–จ๊นŒ ํ•˜๋Š” ๊ฐœ์ธ์  ์˜๊ฒฌ์ž…๋‹ˆ๋‹ค!
@@ -0,0 +1,25 @@ +package christmas.constant; + +public enum Badge { + NONE("์—†์Œ", 0), + STAR("๋ณ„", 5_000), + TREE("ํŠธ๋ฆฌ", 10_000), + SANTA("์‚ฐํƒ€", 20_000); + + + private final String badgeName; + private final long prize; + + Badge(String badgeName, long prize){ + this.badgeName = badgeName; + this.prize = prize; + } + + public String getBadgeName(){ + return badgeName; + } + + public long getPrize(){ + return prize; + } +}
Java
์ด ๋ถ€๋ถ„ ์ฐธ ๊ณ ๋ฏผ ๋งŽ์ด ํ—€๋Š”๋ฐ์š”, ์ €๋„ "์—†์Œ" ๋ฐฐ์ง€๋ฅผ ๋งŒ๋“  ๋’ค ๊ณ ๋ฏผํ•ด๋ณด๋‹ˆ ๋„๋ฉ”์ธ ์ชฝ์—์„œ ์ถœ๋ ฅ ๋กœ์ง์„ ์•Œ์•„์•ผํ•˜๋Š” ๊ฒƒ ๊ฐ™์•„์„œ ์—†์Œ ๋ฐฐ์ง€๋ฅผ ์‚ญ์ œํ•˜๊ณ , Dto์— ๋น„์–ด์žˆ๋Š” badgeName ๊ฐ’์„ ๋„ฃ๋Š” ์‹์œผ๋กœ ๊ตฌํ˜„ํ•œ ํ›„ OutputView์—์„œ ์ „๋‹ฌ๋ฐ›์€ ์ด๋ฒคํŠธ ๋ฐฐ์ง€ ๊ฐ’์ด ๋น„์–ด์žˆ๋Š” String์ด๋ฉด ์—†์• ๋Š” ์‹์œผ๋กœ ์ฒ˜๋ฆฌํ–ˆ์Šต๋‹ˆ๋‹ค. ์ˆ˜์ง„๋‹˜์€ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -0,0 +1,41 @@ +package christmas.constant; + +public enum Menu { + YANGSONGSOUP("์–‘์†ก์ด์ˆ˜ํ”„", 6000, MenuType.APPETIZER), + TAPAS("ํƒ€ํŒŒ์Šค", 5500, MenuType.APPETIZER), + CAESAR_SALAD("์‹œ์ €์ƒ๋Ÿฌ๋“œ", 8000, MenuType.APPETIZER), + + T_BONE_STEAK("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 55000, MenuType.MAIN), + BBQ_RIB("๋ฐ”๋น„ํ๋ฆฝ", 54000, MenuType.MAIN), + SEAFOOD_PASTA("ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", 35000, MenuType.MAIN), + CHRISTMAS_PASTA("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", 25000, MenuType.MAIN), + + CHOCO_CAKE("์ดˆ์ฝ”์ผ€์ดํฌ", 15000, MenuType.DESSERT), + ICE_CREAM("์•„์ด์Šคํฌ๋ฆผ", 5000, MenuType.DESSERT), + + ZERO_COLA("์ œ๋กœ์ฝœ๋ผ", 3000, MenuType.BEVERAGE), + RED_WINE("๋ ˆ๋“œ์™€์ธ", 60000, MenuType.BEVERAGE), + CHAMPAGNE("์ƒดํŽ˜์ธ", 25000, MenuType.BEVERAGE); + + private final String name; + private final int price; + private final MenuType menuType; + + Menu(String name, int price, MenuType menuType) { + this.name = name; + this.price = price; + this.menuType = menuType; + } + + public String getName() { + return name; + } + + public int getPrice() { + return price; + } + + public MenuType getMenuType() { + return menuType; + } +}
Java
MenuType์„ static import ํ•˜๋ฉด ์ข€ ๋” ์งง๊ฒŒ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ์„๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,74 @@ +package christmas.controller; + +import christmas.constant.Menu; +import christmas.domain.BenefitStorage; +import christmas.dto.BenefitResult; +import christmas.domain.Customer; +import christmas.domain.EventPlanner; +import christmas.dto.OrderMenu; +import christmas.exception.ExceptionHandler; +import christmas.view.InputView; +import christmas.view.OutputView; +import java.util.Map; + +public class ChristmasController { + + private final ExceptionHandler handler; + private Customer customer; + private EventPlanner eventPlanner; + + + public ChristmasController(ExceptionHandler handler){ + this.handler = handler; + } + + public void service(){ + order(); + searchPromotion(customer); + } + + public void order(){ + int date = getDate(); + Map<Menu, Integer> menu = getMenu(); + customer = new Customer(date, menu); + + displayOrder(date, menu); + } + + private int getDate(){ + return handler.getResult(InputView::readVisitDate); + } + + private Map<Menu, Integer> getMenu(){ + return handler.getResult(InputView::readMenu); + } + + private void searchPromotion(Customer customer){ + eventPlanner = new EventPlanner(); + eventPlanner.findPromotion(customer); + + BenefitStorage benefitStorage = storeBenefits(); + previewEventBenefits(benefitStorage); + } + + private BenefitStorage storeBenefits(){ + if(eventPlanner.hasGiftMenu()){ + return new BenefitStorage(customer.getTotalOrderAmount(), true, eventPlanner.getPromotionResult()); + } + return new BenefitStorage(customer.getTotalOrderAmount(), false, eventPlanner.getPromotionResult()); + } + + private void displayOrder(int date, Map<Menu, Integer> menu){ + OrderMenu orderMenu = new OrderMenu(date, menu); + OutputView.printOrder(orderMenu); + } + + + private void previewEventBenefits(BenefitStorage benefitStorage){ + BenefitResult benefitResult = new BenefitResult(benefitStorage.getBeforeDiscountAmount(), + benefitStorage.isGiftMenu(), benefitStorage.getPromotionResult(), benefitStorage.totalBenefitAmount(), + benefitStorage.afterDiscountAmount(), benefitStorage.determineBadge()); + OutputView.printPreview(benefitResult); + } + +}
Java
์‚ฌ์†Œํ•˜์ง€๋งŒ ๋„ค์ด๋ฐ์„ `OrderedMenu` ๋กœ ํ•˜๋ฉด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,74 @@ +package christmas.controller; + +import christmas.constant.Menu; +import christmas.domain.BenefitStorage; +import christmas.dto.BenefitResult; +import christmas.domain.Customer; +import christmas.domain.EventPlanner; +import christmas.dto.OrderMenu; +import christmas.exception.ExceptionHandler; +import christmas.view.InputView; +import christmas.view.OutputView; +import java.util.Map; + +public class ChristmasController { + + private final ExceptionHandler handler; + private Customer customer; + private EventPlanner eventPlanner; + + + public ChristmasController(ExceptionHandler handler){ + this.handler = handler; + } + + public void service(){ + order(); + searchPromotion(customer); + } + + public void order(){ + int date = getDate(); + Map<Menu, Integer> menu = getMenu(); + customer = new Customer(date, menu); + + displayOrder(date, menu); + } + + private int getDate(){ + return handler.getResult(InputView::readVisitDate); + } + + private Map<Menu, Integer> getMenu(){ + return handler.getResult(InputView::readMenu); + } + + private void searchPromotion(Customer customer){ + eventPlanner = new EventPlanner(); + eventPlanner.findPromotion(customer); + + BenefitStorage benefitStorage = storeBenefits(); + previewEventBenefits(benefitStorage); + } + + private BenefitStorage storeBenefits(){ + if(eventPlanner.hasGiftMenu()){ + return new BenefitStorage(customer.getTotalOrderAmount(), true, eventPlanner.getPromotionResult()); + } + return new BenefitStorage(customer.getTotalOrderAmount(), false, eventPlanner.getPromotionResult()); + } + + private void displayOrder(int date, Map<Menu, Integer> menu){ + OrderMenu orderMenu = new OrderMenu(date, menu); + OutputView.printOrder(orderMenu); + } + + + private void previewEventBenefits(BenefitStorage benefitStorage){ + BenefitResult benefitResult = new BenefitResult(benefitStorage.getBeforeDiscountAmount(), + benefitStorage.isGiftMenu(), benefitStorage.getPromotionResult(), benefitStorage.totalBenefitAmount(), + benefitStorage.afterDiscountAmount(), benefitStorage.determineBadge()); + OutputView.printPreview(benefitResult); + } + +}
Java
`customer = new Customer(getDate(), getMenu());` ๋กœ ํ•œ๋ฒˆ์— ํ•ด๋„ ์ข‹์„ ๊ฑฐ ๊ฐ™์•„์š”. `getDate()` ๋‚˜ `getMenu()` ๋‘˜ ๋‹ค ๋ฉ”์„œ๋“œ ์ด๋ฆ„์œผ๋กœ ๋ญ๋ฅผ ํ•˜๋Š”์ง€ ์ •ํ™•ํžˆ ์•Œ ์ˆ˜ ์žˆ์–ด๋ณด์ž…๋‹ˆ๋‹ค.
@@ -0,0 +1,55 @@ +package christmas.domain; + +import christmas.constant.Badge; +import christmas.constant.Menu; +import christmas.domain.promotion.ChristmasPromotion; +import java.util.Arrays; +import java.util.HashMap; + +public class BenefitStorage { + + private final long beforeDiscountAmount; + private final boolean giftMenu; + private final HashMap<ChristmasPromotion, Long> promotionResult; + + public BenefitStorage(long beforeDiscountAmount, boolean giftMenu, HashMap<ChristmasPromotion, Long> promotionResult){ + this.beforeDiscountAmount = beforeDiscountAmount; + this.giftMenu = giftMenu; + this.promotionResult = promotionResult; + } + + public long totalBenefitAmount() { + return promotionResult.values().stream().mapToLong(Long::longValue).sum(); + } + + public long afterDiscountAmount() { + long totalBenefit = totalBenefitAmount(); + + if (giftMenu) { + totalBenefit -= Menu.CHAMPAGNE.getPrice(); + } + + return beforeDiscountAmount - totalBenefit; + } + + public Badge determineBadge() { + long totalBenefit = totalBenefitAmount(); + + return Arrays.stream(Badge.values()) + .filter(badge -> totalBenefit >= badge.getPrize()) + .reduce((first, second) -> second) + .orElse(Badge.NONE); + } + + public long getBeforeDiscountAmount() { + return beforeDiscountAmount; + } + + public boolean isGiftMenu() { + return giftMenu; + } + + public HashMap<ChristmasPromotion, Long> getPromotionResult() { + return promotionResult; + } +}
Java
Map ํƒ€์ž…์œผ๋กœ ์ธ์Šคํ„ด์Šค ๋ณ€์ˆ˜๋ฅผ ๊ฐ€์ง€๋ฉด ์ถ”ํ›„ ์„ธ๋ถ€ ๊ตฌํ˜„ ์ž๋ฃŒ๊ตฌ์กฐ๊ฐ€ ๋ฐ”๋€” ๋•Œ ๋Šฅ๋™์ ์œผ๋กœ ๋Œ€์ฒ˜ํ•  ์ˆ˜ ์žˆ์„๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,55 @@ +package christmas.domain; + +import christmas.constant.Badge; +import christmas.constant.Menu; +import christmas.domain.promotion.ChristmasPromotion; +import java.util.Arrays; +import java.util.HashMap; + +public class BenefitStorage { + + private final long beforeDiscountAmount; + private final boolean giftMenu; + private final HashMap<ChristmasPromotion, Long> promotionResult; + + public BenefitStorage(long beforeDiscountAmount, boolean giftMenu, HashMap<ChristmasPromotion, Long> promotionResult){ + this.beforeDiscountAmount = beforeDiscountAmount; + this.giftMenu = giftMenu; + this.promotionResult = promotionResult; + } + + public long totalBenefitAmount() { + return promotionResult.values().stream().mapToLong(Long::longValue).sum(); + } + + public long afterDiscountAmount() { + long totalBenefit = totalBenefitAmount(); + + if (giftMenu) { + totalBenefit -= Menu.CHAMPAGNE.getPrice(); + } + + return beforeDiscountAmount - totalBenefit; + } + + public Badge determineBadge() { + long totalBenefit = totalBenefitAmount(); + + return Arrays.stream(Badge.values()) + .filter(badge -> totalBenefit >= badge.getPrize()) + .reduce((first, second) -> second) + .orElse(Badge.NONE); + } + + public long getBeforeDiscountAmount() { + return beforeDiscountAmount; + } + + public boolean isGiftMenu() { + return giftMenu; + } + + public HashMap<ChristmasPromotion, Long> getPromotionResult() { + return promotionResult; + } +}
Java
์–ด์ฐŒ๋ณด๋ฉด Dto์— ๊ฐ€๊นŒ์šด ์„ฑ๊ฒฉ์„ ๊ฐ€์ง€๋Š” ํด๋ž˜์Šค์ธ๋ฐ ๋„๋ฉ”์ธ ๋กœ์ง์„ ๋‹ค ๋„ฃ์–ด๋‘” ๋А๋‚Œ์„ ๋ฐ›์•˜์Šต๋‹ˆ๋‹ค. ๊ฒฐ๊ตญ ์ถœ๋ ฅ๋•Œ ํ•„์š”ํ•œ ์ž๋ฃŒ๋“ค์„ ๋‹ค ๊ฐ€์ง€๊ณ  ์žˆ์–ด์„œ ๋„๋ฉ”์ธ์„ ๋‹ค๋ฅธ ๋ฐฉ์‹์œผ๋กœ ๋ถ„๋ฆฌํ•ด๋ณด๋Š” ๊ฒƒ์„ ๊ณ ๋ คํ•ด๋ณด๋ฉด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,71 @@ +package christmas.domain; + +import christmas.constant.MenuType; +import christmas.constant.PromotionType; +import christmas.domain.promotion.ChristmasPromotion; +import christmas.domain.promotion.DdayPromotion; +import christmas.domain.promotion.GiftPromotion; +import christmas.domain.promotion.SpecialPromotion; +import christmas.domain.promotion.WeekDayPromotion; +import christmas.domain.promotion.WeekendPromotion; +import java.util.HashMap; +import java.util.Map; + +public class EventPlanner { + private final HashMap<ChristmasPromotion, Long> promotionResult; + + public EventPlanner(){ + promotionResult = new HashMap<>(); + promotionResult.put(new DdayPromotion(), 0L); + promotionResult.put(new GiftPromotion(), 0L); + promotionResult.put(new SpecialPromotion(), 0L); + promotionResult.put(new WeekDayPromotion(), 0L); + promotionResult.put(new WeekendPromotion(), 0L); + } + + public void findPromotion(Customer customer){ + for(ChristmasPromotion promotion : promotionResult.keySet()){ + checkPromotionConditions(promotion, customer); + } + } + + public boolean hasGiftMenu(){ + return promotionResult.entrySet() + .stream() + .filter(entry -> entry.getKey() instanceof GiftPromotion) + .mapToLong(Map.Entry::getValue) + .sum() > 0; + } + + public HashMap<ChristmasPromotion, Long> getPromotionResult(){ + return promotionResult; + } + + private void checkPromotionConditions(ChristmasPromotion promotion, Customer customer){ + long discount = customer.applicablePromotion(promotion); + + if (isContainWeekOrWeekend(promotion)) { + discount *= checkMenuCount(customer, promotion.getPromotionType()); + } + promotionResult.put(promotion, promotionResult.get(promotion) + discount); + } + + private int checkMenuCount(Customer customer, PromotionType promotionType) { + Map<PromotionType, MenuType> promotionTypeMenuTypeMap = Map.of( + PromotionType.WEEKDAY, MenuType.DESSERT, + PromotionType.WEEKEND, MenuType.MAIN + ); + + MenuType menuType = promotionTypeMenuTypeMap.getOrDefault(promotionType, MenuType.NONE); + return customer.countMenuType(menuType); + } + + private boolean isContainWeekOrWeekend(ChristmasPromotion promotion){ + if(promotion.getPromotionType() == PromotionType.WEEKDAY + || promotion.getPromotionType() == PromotionType.WEEKEND) + return true; + + return false; + } + +}
Java
๋ณ€์ˆ˜ ๋ช…์— Map ์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ๋ณด๋‹ค๋Š” `PromotionsAppliedToEachMenu` ์™€ ๊ฐ™์ด ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,43 @@ +package christmas.domain.promotion; + +import christmas.constant.PromotionItem; +import christmas.constant.PromotionType; +import java.util.Arrays; + +public class DdayPromotion extends ChristmasPromotion{ + + private static final int START_DATE = 1; + private static final int END_DATE = 25; + private static final int INIT_DISCOUNT_AMOUNT = 1000; + private static final int MIN_ORDER_AMOUNT = 10000; + + + public DdayPromotion(){ + this.period = Arrays.asList(START_DATE, END_DATE); + this.targetItems = PromotionItem.TOTAL_ORDER_AMOUNT; + this.discountAmount = INIT_DISCOUNT_AMOUNT; + this.promotionType = PromotionType.DDAY; + } + + @Override + public long applyPromotion(int data, long orderAmount){ + if(isApplicable(data) && isEligibleForPromotion(orderAmount)){ + return getDiscountAmount(data); + } + return 0L; + } + + @Override + protected boolean isApplicable(int date) { + return date >= period.get(0) && date <= period.get(1); + } + + @Override + protected boolean isEligibleForPromotion(long orderAmount){ + return orderAmount >= MIN_ORDER_AMOUNT; + } + + public long getDiscountAmount(int date) { + return discountAmount + 100L * (date - 1); + } +}
Java
๋งค์ง๋„˜๋ฒ„๋ฅผ ์ƒ์ˆ˜๋กœ ๋‘๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,39 @@ +package christmas.domain.promotion; + +import christmas.constant.PromotionItem; +import christmas.constant.PromotionType; +import java.util.Arrays; + +public class GiftPromotion extends ChristmasPromotion{ + + private static final long PRICETHRESHOLD = 120000; + private static final int START_DATE = 1; + private static final int END_DATE = 31; + private static final int INIT_DISCOUNT_AMOUNT = 25000; + + public GiftPromotion(){ + this.period = Arrays.asList(START_DATE, END_DATE); + this.targetItems = PromotionItem.GIFT_CHAMPAGNE; + this.discountAmount = INIT_DISCOUNT_AMOUNT; + this.promotionType = PromotionType.GIFT; + } + + @Override + public long applyPromotion(int data, long orderAmount){ + if(isApplicable(data) && isEligibleForPromotion(orderAmount)){ + return getDiscountAmount(); + } + return 0L; + } + + @Override + protected boolean isApplicable(int date) { + return date >= period.get(0) && date <= period.get(1); + } + + @Override + protected boolean isEligibleForPromotion(long orderAmount){ + return orderAmount >= PRICETHRESHOLD; + } + +}
Java
`PRICE_THRESHOLD` ์™€ ๊ฐ™์ด ๋‚˜๋ˆ ์ฃผ๋ฉด ๊ฐ€๋…์„ฑ์ด ๋” ์ข‹์•„์งˆ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,38 @@ +package christmas.domain.promotion; + +import christmas.constant.PromotionItem; +import christmas.constant.PromotionType; +import java.util.Arrays; + +public class SpecialPromotion extends ChristmasPromotion{ + + private static final int INIT_DISCOUNT_AMOUNT = 1000; + private static final int MIN_ORDER_AMOUNT = 10000; + + public SpecialPromotion(){ + this.period = Arrays.asList(3, 10, 17, 24, 25, 31); + this.targetItems = PromotionItem.TOTAL_ORDER_AMOUNT; + this.discountAmount = INIT_DISCOUNT_AMOUNT; + this.promotionType = PromotionType.SPECIAL; + } + + @Override + public long applyPromotion(int data, long orderAmount){ + if(isApplicable(data) && isEligibleForPromotion(orderAmount)){ + return getDiscountAmount(); + } + return 0L; + } + + @Override + protected boolean isApplicable(int date) { + return period.contains(date); + } + + @Override + protected boolean isEligibleForPromotion(long orderAmount){ + return orderAmount >= MIN_ORDER_AMOUNT; + } + + +}
Java
์š”๊ฒƒ๋„ ๋งค์ง๋„˜๋ฒ„! ํ˜น์€ 1~31 ๊ฐ’ ์ค‘ 7๋กœ ๋‚˜๋ˆ„์—ˆ์„ ๋•Œ ๋‚˜๋จธ์ง€๊ฐ€ 3์ธ ๋‚ ์งœ๋กœ ์ดˆ๊ธฐํ™”ํ•ด์ค˜๋„ ์ข‹์„ ๊ฑฐ ๊ฐ™์•„์š”
@@ -0,0 +1,38 @@ +package christmas.domain.promotion; + +import christmas.constant.PromotionItem; +import christmas.constant.PromotionType; +import java.util.Arrays; + +public class SpecialPromotion extends ChristmasPromotion{ + + private static final int INIT_DISCOUNT_AMOUNT = 1000; + private static final int MIN_ORDER_AMOUNT = 10000; + + public SpecialPromotion(){ + this.period = Arrays.asList(3, 10, 17, 24, 25, 31); + this.targetItems = PromotionItem.TOTAL_ORDER_AMOUNT; + this.discountAmount = INIT_DISCOUNT_AMOUNT; + this.promotionType = PromotionType.SPECIAL; + } + + @Override + public long applyPromotion(int data, long orderAmount){ + if(isApplicable(data) && isEligibleForPromotion(orderAmount)){ + return getDiscountAmount(); + } + return 0L; + } + + @Override + protected boolean isApplicable(int date) { + return period.contains(date); + } + + @Override + protected boolean isEligibleForPromotion(long orderAmount){ + return orderAmount >= MIN_ORDER_AMOUNT; + } + + +}
Java
๊ณต๋ฐฑ๋„ ์ฝ”๋”ฉ์ปจ๋ฒค์…˜์ด๋ผ, ๋‹ค๋ฅธ ํด๋ž˜์Šค ํŒŒ์ผ๊ณผ ๋งž์ถฐ์ฃผ๋Š”๊ฒŒ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,47 @@ +package christmas.domain.promotion; + +import christmas.constant.PromotionItem; +import christmas.constant.PromotionType; +import java.time.LocalDate; +import java.time.DayOfWeek; +import java.util.Arrays; + +public class WeekDayPromotion extends ChristmasPromotion{ + + private static final int START_DATE = 1; + private static final int END_DATE = 31; + private static final int INIT_DISCOUNT_AMOUNT = 2023; + private static final int MIN_ORDER_AMOUNT = 10000; + + public WeekDayPromotion(){ + this.period = Arrays.asList(START_DATE, END_DATE); + this.targetItems = PromotionItem.DESSERT_MENU; + this.discountAmount = INIT_DISCOUNT_AMOUNT; + this.promotionType = PromotionType.WEEKDAY; + } + + @Override + public long applyPromotion(int data, long orderAmount){ + if(isApplicable(data) && isEligibleForPromotion(orderAmount)){ + return getDiscountAmount(); + } + return 0L; + } + + @Override + protected boolean isApplicable(int date) { + LocalDate orderDate = LocalDate.of(2023, 12, date); + + return isWeekday(orderDate); + } + + @Override + protected boolean isEligibleForPromotion(long orderAmount){ + return orderAmount >= MIN_ORDER_AMOUNT; + } + + private boolean isWeekday(LocalDate date) { + DayOfWeek dayOfWeek = date.getDayOfWeek(); + return dayOfWeek != DayOfWeek.FRIDAY && dayOfWeek != DayOfWeek.SATURDAY; + } +}
Java
๋‚ด๋ถ€ ์ƒ์ˆ˜๋กœ ๋‘๋Š” ๊ฒƒ๋ณด๋‹ค, ์ƒ์„ฑ๋  ๋•Œ ์œ„์˜ ์ƒ์ˆ˜ ๊ฐ’์œผ๋กœ ์ดˆ๊ธฐํ™” ์‹œํ‚ค๊ณ  ๊ฐ์ฒด๋ฅผ ์‹ฑ๊ธ€ํ†ค์œผ๋กœ ๊ด€๋ฆฌํ•˜๋Š” ๊ฒƒ๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”
@@ -0,0 +1,7 @@ +package christmas.exception; + +import java.util.function.Supplier; + +public interface ExceptionHandler { + <T> T getResult(Supplier<T> supplier); +}
Java
`Supplier` ๋ผ๋Š” ๋ฌธ๋ฒ•์€ ์ฒ˜์Œ๋ณด๋„ค์š”! ํ•จ์ˆ˜ํ˜• ํ”„๋กœ๊ทธ๋ž˜๋ฐ? ์ธ๊ฐ€ ๋ณด๋„ค์š” ใ…Žใ…Ž ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค.
@@ -0,0 +1,28 @@ +package christmas.exception; + +import christmas.view.OutputView; +import java.util.function.Supplier; + +public class RetryExceptionHandler implements ExceptionHandler{ + + @Override + public <T> T getResult(Supplier<T> supplier) { + while (true) { + try { + return supplier.get(); + } catch (IllegalArgumentException e) { + printException(e); + } finally { + afterHandlingException(); + } + } + } + + private void printException(IllegalArgumentException e) { + OutputView.printErrorMessage(e); + } + + private void afterHandlingException() { + OutputView.printEmptyLine(); + } +}
Java
์ด๋ ‡๊ฒŒ ํ•˜๋ฉด try-catch๋ฌธ์˜ ์ค‘๋ณต ๋กœ์ง์„ ๋บ„ ์ˆ˜ ์žˆ๊ฒ ๊ตฐ์š”.!
@@ -0,0 +1,119 @@ +package christmas.validator; + +import christmas.constant.Menu; +import christmas.constant.MenuType; +import christmas.exception.ErrorCode; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class InputValidator { + + private static int START_DATE = 1; + private static int END_DATE = 31; + private static String COMMA = ","; + private static String HYPHEN = "-"; + private static int MENU_FORMAT_LENGTH = 2; + private static int MINIMUM_ORDER_COUNT = 1; + private static int MAXIMUN_ORDER_COUNT = 20; + + public static void validateVisitDate(String input){ + validateInteger(input); + validateNumberInRange(Integer.parseInt(input)); + } + + public static Map<Menu, Integer> validateMenuOrder(String input, Map<Menu, Integer> orderMenu){ + String[] orders = input.split(COMMA); + Set<Menu> uniqueMenu = new HashSet<>(); + + for (String order : orders) { + validate(order, orderMenu, uniqueMenu); + } + + validateOnlyBeverage(orderMenu); + validateMaxOrder(orderMenu); + + return orderMenu; + } + + private static void validate(String order, Map<Menu, Integer> orderMenu, Set<Menu> uniqueMenu){ + String[] parts = validateMenuOrderFormat(order.trim()); + + String menuName = parts[0]; + String quantity = parts[1]; + + Menu menu = getMenuByName(menuName); + + validateMenuFound(menu); + validateMinimumOrder(quantity); + validateDuplicateMenu(menu, uniqueMenu); + + orderMenu.put(menu, Integer.parseInt(quantity)); + } + + private static void validateInteger(String input){ + if(!input.chars().allMatch(Character::isDigit)){ + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + } + + private static void validateNumberInRange(int input){ + if(input > END_DATE || input < START_DATE) + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + + private static String[] validateMenuOrderFormat(String orders){ + String[] parts = orders.split(HYPHEN); + if (parts.length != MENU_FORMAT_LENGTH) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + return parts; + } + + private static void validateMenuFound(Menu menu){ + if(menu == null) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMinimumOrder(String quantity){ + if(!quantity.chars().allMatch(Character::isDigit)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + if(Integer.parseInt(quantity) < MINIMUM_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMaxOrder(Map<Menu, Integer> orderMenu){ + int orderCount = 0; + for(Menu menu: orderMenu.keySet()) { + orderCount += orderMenu.get(menu); + } + + if(orderCount > MAXIMUN_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateDuplicateMenu(Menu menu, Set<Menu> uniqueMenu){ + if(!uniqueMenu.add(menu)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + + private static void validateOnlyBeverage(Map<Menu, Integer> orderMenu){ + boolean allBeverages = orderMenu.keySet().stream() + .allMatch(menu -> menu.getMenuType() == MenuType.BEVERAGE); + + if (allBeverages) { + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + } + + private static Menu getMenuByName(String name) { + for (Menu menu : Menu.values()) { + if (menu.getName().equalsIgnoreCase(name)) { + return menu; + } + } + return null; + } +}
Java
ํ•ด๋‹น ๋ฉ”์„œ๋“œ๋Š” Map์„ ๋ฐ˜ํ™˜ํ•˜๊ธฐ ๋ณด๋‹ค๋Š” void ํ˜•์‹์œผ๋กœ ์˜ˆ์™ธ๋ฅผ ๋˜์งˆ ๊ฒƒ ๊ฐ™์€ ๋„ค์ด๋ฐ์ด๋ผ ๋А๊ปด์ ธ์š”. ์—ญํ• ์„ ๊ฒ€์ฆ ๋ฐ ๋ฐ˜ํ™˜ ๋‘๊ฐœ๋ฅผ ํ•˜๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ ๊ฐ ์—ญํ• ์— ๋งž๋Š” ๋ฉ”์„œ๋“œ๋กœ ๋‚˜๋ˆ ๋ณด๋Š” ๊ฒƒ์€ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -0,0 +1,119 @@ +package christmas.validator; + +import christmas.constant.Menu; +import christmas.constant.MenuType; +import christmas.exception.ErrorCode; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class InputValidator { + + private static int START_DATE = 1; + private static int END_DATE = 31; + private static String COMMA = ","; + private static String HYPHEN = "-"; + private static int MENU_FORMAT_LENGTH = 2; + private static int MINIMUM_ORDER_COUNT = 1; + private static int MAXIMUN_ORDER_COUNT = 20; + + public static void validateVisitDate(String input){ + validateInteger(input); + validateNumberInRange(Integer.parseInt(input)); + } + + public static Map<Menu, Integer> validateMenuOrder(String input, Map<Menu, Integer> orderMenu){ + String[] orders = input.split(COMMA); + Set<Menu> uniqueMenu = new HashSet<>(); + + for (String order : orders) { + validate(order, orderMenu, uniqueMenu); + } + + validateOnlyBeverage(orderMenu); + validateMaxOrder(orderMenu); + + return orderMenu; + } + + private static void validate(String order, Map<Menu, Integer> orderMenu, Set<Menu> uniqueMenu){ + String[] parts = validateMenuOrderFormat(order.trim()); + + String menuName = parts[0]; + String quantity = parts[1]; + + Menu menu = getMenuByName(menuName); + + validateMenuFound(menu); + validateMinimumOrder(quantity); + validateDuplicateMenu(menu, uniqueMenu); + + orderMenu.put(menu, Integer.parseInt(quantity)); + } + + private static void validateInteger(String input){ + if(!input.chars().allMatch(Character::isDigit)){ + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + } + + private static void validateNumberInRange(int input){ + if(input > END_DATE || input < START_DATE) + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + + private static String[] validateMenuOrderFormat(String orders){ + String[] parts = orders.split(HYPHEN); + if (parts.length != MENU_FORMAT_LENGTH) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + return parts; + } + + private static void validateMenuFound(Menu menu){ + if(menu == null) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMinimumOrder(String quantity){ + if(!quantity.chars().allMatch(Character::isDigit)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + if(Integer.parseInt(quantity) < MINIMUM_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMaxOrder(Map<Menu, Integer> orderMenu){ + int orderCount = 0; + for(Menu menu: orderMenu.keySet()) { + orderCount += orderMenu.get(menu); + } + + if(orderCount > MAXIMUN_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateDuplicateMenu(Menu menu, Set<Menu> uniqueMenu){ + if(!uniqueMenu.add(menu)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + + private static void validateOnlyBeverage(Map<Menu, Integer> orderMenu){ + boolean allBeverages = orderMenu.keySet().stream() + .allMatch(menu -> menu.getMenuType() == MenuType.BEVERAGE); + + if (allBeverages) { + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + } + + private static Menu getMenuByName(String name) { + for (Menu menu : Menu.values()) { + if (menu.getName().equalsIgnoreCase(name)) { + return menu; + } + } + return null; + } +}
Java
์กฐ๊ฑด๋ฌธ์˜ ์กฐ๊ฑด์„ ํ•˜๋‚˜์˜ ๋ฉ”์„œ๋“œ๋กœ ๋นผ๋Š” ๊ฒƒ๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,119 @@ +package christmas.validator; + +import christmas.constant.Menu; +import christmas.constant.MenuType; +import christmas.exception.ErrorCode; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class InputValidator { + + private static int START_DATE = 1; + private static int END_DATE = 31; + private static String COMMA = ","; + private static String HYPHEN = "-"; + private static int MENU_FORMAT_LENGTH = 2; + private static int MINIMUM_ORDER_COUNT = 1; + private static int MAXIMUN_ORDER_COUNT = 20; + + public static void validateVisitDate(String input){ + validateInteger(input); + validateNumberInRange(Integer.parseInt(input)); + } + + public static Map<Menu, Integer> validateMenuOrder(String input, Map<Menu, Integer> orderMenu){ + String[] orders = input.split(COMMA); + Set<Menu> uniqueMenu = new HashSet<>(); + + for (String order : orders) { + validate(order, orderMenu, uniqueMenu); + } + + validateOnlyBeverage(orderMenu); + validateMaxOrder(orderMenu); + + return orderMenu; + } + + private static void validate(String order, Map<Menu, Integer> orderMenu, Set<Menu> uniqueMenu){ + String[] parts = validateMenuOrderFormat(order.trim()); + + String menuName = parts[0]; + String quantity = parts[1]; + + Menu menu = getMenuByName(menuName); + + validateMenuFound(menu); + validateMinimumOrder(quantity); + validateDuplicateMenu(menu, uniqueMenu); + + orderMenu.put(menu, Integer.parseInt(quantity)); + } + + private static void validateInteger(String input){ + if(!input.chars().allMatch(Character::isDigit)){ + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + } + + private static void validateNumberInRange(int input){ + if(input > END_DATE || input < START_DATE) + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + + private static String[] validateMenuOrderFormat(String orders){ + String[] parts = orders.split(HYPHEN); + if (parts.length != MENU_FORMAT_LENGTH) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + return parts; + } + + private static void validateMenuFound(Menu menu){ + if(menu == null) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMinimumOrder(String quantity){ + if(!quantity.chars().allMatch(Character::isDigit)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + if(Integer.parseInt(quantity) < MINIMUM_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMaxOrder(Map<Menu, Integer> orderMenu){ + int orderCount = 0; + for(Menu menu: orderMenu.keySet()) { + orderCount += orderMenu.get(menu); + } + + if(orderCount > MAXIMUN_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateDuplicateMenu(Menu menu, Set<Menu> uniqueMenu){ + if(!uniqueMenu.add(menu)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + + private static void validateOnlyBeverage(Map<Menu, Integer> orderMenu){ + boolean allBeverages = orderMenu.keySet().stream() + .allMatch(menu -> menu.getMenuType() == MenuType.BEVERAGE); + + if (allBeverages) { + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + } + + private static Menu getMenuByName(String name) { + for (Menu menu : Menu.values()) { + if (menu.getName().equalsIgnoreCase(name)) { + return menu; + } + } + return null; + } +}
Java
null ์„ ์ง์ ‘ ๋‹ค๋ฃจ๋Š” ๊ฒƒ๋ณด๋‹ค, Menu ๋‚ด์—์„œ ์ด๋ฆ„์„ ๋ฐ›์•„์„œ Menu์˜ ์œ ๋ฌด๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฉ”์„œ๋“œ๋ฅผ ๋งŒ๋“œ๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,119 @@ +package christmas.validator; + +import christmas.constant.Menu; +import christmas.constant.MenuType; +import christmas.exception.ErrorCode; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class InputValidator { + + private static int START_DATE = 1; + private static int END_DATE = 31; + private static String COMMA = ","; + private static String HYPHEN = "-"; + private static int MENU_FORMAT_LENGTH = 2; + private static int MINIMUM_ORDER_COUNT = 1; + private static int MAXIMUN_ORDER_COUNT = 20; + + public static void validateVisitDate(String input){ + validateInteger(input); + validateNumberInRange(Integer.parseInt(input)); + } + + public static Map<Menu, Integer> validateMenuOrder(String input, Map<Menu, Integer> orderMenu){ + String[] orders = input.split(COMMA); + Set<Menu> uniqueMenu = new HashSet<>(); + + for (String order : orders) { + validate(order, orderMenu, uniqueMenu); + } + + validateOnlyBeverage(orderMenu); + validateMaxOrder(orderMenu); + + return orderMenu; + } + + private static void validate(String order, Map<Menu, Integer> orderMenu, Set<Menu> uniqueMenu){ + String[] parts = validateMenuOrderFormat(order.trim()); + + String menuName = parts[0]; + String quantity = parts[1]; + + Menu menu = getMenuByName(menuName); + + validateMenuFound(menu); + validateMinimumOrder(quantity); + validateDuplicateMenu(menu, uniqueMenu); + + orderMenu.put(menu, Integer.parseInt(quantity)); + } + + private static void validateInteger(String input){ + if(!input.chars().allMatch(Character::isDigit)){ + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + } + + private static void validateNumberInRange(int input){ + if(input > END_DATE || input < START_DATE) + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + + private static String[] validateMenuOrderFormat(String orders){ + String[] parts = orders.split(HYPHEN); + if (parts.length != MENU_FORMAT_LENGTH) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + return parts; + } + + private static void validateMenuFound(Menu menu){ + if(menu == null) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMinimumOrder(String quantity){ + if(!quantity.chars().allMatch(Character::isDigit)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + if(Integer.parseInt(quantity) < MINIMUM_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMaxOrder(Map<Menu, Integer> orderMenu){ + int orderCount = 0; + for(Menu menu: orderMenu.keySet()) { + orderCount += orderMenu.get(menu); + } + + if(orderCount > MAXIMUN_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateDuplicateMenu(Menu menu, Set<Menu> uniqueMenu){ + if(!uniqueMenu.add(menu)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + + private static void validateOnlyBeverage(Map<Menu, Integer> orderMenu){ + boolean allBeverages = orderMenu.keySet().stream() + .allMatch(menu -> menu.getMenuType() == MenuType.BEVERAGE); + + if (allBeverages) { + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + } + + private static Menu getMenuByName(String name) { + for (Menu menu : Menu.values()) { + if (menu.getName().equalsIgnoreCase(name)) { + return menu; + } + } + return null; + } +}
Java
์ด ๋ถ€๋ถ„์—์„œ Exception์„ ๋˜์ ธ์ฃผ๋Š” ๊ฒƒ๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,44 @@ +package christmas.view; + +import christmas.constant.Badge; +import christmas.constant.OutputMessage; +import christmas.domain.promotion.ChristmasPromotion; +import java.util.HashMap; + +public class BenefitsView { + + public static String giftMenuOutputStatement(boolean giftMenu){ + if(giftMenu) + return OutputMessage.CHAMPAGNE.getMessage(); + + return OutputMessage.DOES_NOT_EXIST.getMessage(); + } + + public static String promotionResultOutputStatement(long totalBenefitAmount, HashMap<ChristmasPromotion, Long> promotionResult){ + if(totalBenefitAmount == 0) + return OutputMessage.DOES_NOT_EXIST.getMessage(); + + return findPromotionDetail(promotionResult).toString(); + } + + public static String badgeOutputStatement(Badge badge){ + if(badge == Badge.NONE) + return OutputMessage.DOES_NOT_EXIST.getMessage(); + return badge.getBadgeName(); + } + + private static StringBuilder findPromotionDetail(HashMap<ChristmasPromotion, Long> promotionResult){ + StringBuilder sb = new StringBuilder(); + for(ChristmasPromotion promotion: promotionResult.keySet()){ + long discount = promotionResult.get(promotion); + if(discount == 0) continue; + + sb.append(String.format(OutputMessage.BENEFIT_DETAILS.getMessage(), + promotion.getPromotionType().getMessage(), discount)); + } + + if(sb.isEmpty()) + return sb.append(OutputMessage.DOES_NOT_EXIST.getMessage()); + return sb; + } +}
Java
if ๋ฌธ ์„ {} ๋กœ ๊ฐ์‹ธ์ฃผ๋Š”๊ฒŒ ์ฝ”๋”ฉ ์ปจ๋ฒค์…˜์œผ๋กœ ์•Œ๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,74 @@ +package christmas.view; + +import christmas.constant.Badge; +import christmas.constant.Menu; +import christmas.constant.OutputMessage; +import christmas.domain.promotion.ChristmasPromotion; +import christmas.dto.BenefitResult; +import christmas.dto.OrderMenu; +import java.util.HashMap; +import java.util.Map; + +public class OutputView { + + public static void printErrorMessage(IllegalArgumentException e){ + System.out.println(e.getMessage()); + } + + public static void printEmptyLine(){ + System.out.println(); + } + + public static void printOrder(OrderMenu orderMenu){ + printDate(orderMenu.date()); + printEmptyLine(); + printOrderedMenu(orderMenu.menu()); + } + + public static void printPreview(BenefitResult benefits){ + printBeforeDiscountAmount(benefits.beforeDiscountAmount()); + printHasGift(benefits.giftMenu()); + printBenefitsDetail(benefits.beforeDiscountAmount(), benefits.promotionResult()); + printTotalBenefits(benefits.totalBenefitAmount()); + printAfterDiscountAmount(benefits.afterDiscountAmount()); + printBadge(benefits.badge()); + } + + private static void printOrderedMenu(Map<Menu, Integer> orderMenu){ + System.out.println(String.format(OutputMessage.ORDER_MENU_PREFIX.getMessage(), + OrderMenuView.orderMenuOutputStatement(orderMenu))); + } + + private static void printDate(int date){ + System.out.println(String.format(OutputMessage.RESERVATION_DATE.getMessage(), date)); + } + + private static void printBeforeDiscountAmount(long total){ + System.out.println(String.format(OutputMessage.BEFORE_DISCOUNT_AMOUNT.getMessage(), total)); + } + + private static void printHasGift(boolean hasGift){ + System.out.println(String.format(OutputMessage.GIVEAWAY_MENU.getMessage(), + BenefitsView.giftMenuOutputStatement(hasGift))); + + } + + private static void printBenefitsDetail(long price, HashMap<ChristmasPromotion, Long> result){ + System.out.println(String.format(OutputMessage.BENEFIT_DETAILS_PREFIX.getMessage(), + BenefitsView.promotionResultOutputStatement(price, result))); + } + + private static void printTotalBenefits(long price){ + System.out.println(String.format(OutputMessage.TOTAL_BENEFIT_AMOUNT.getMessage(), -price)); + } + + private static void printAfterDiscountAmount(long price){ + System.out.println(String.format(OutputMessage.AFTER_DISCOUNT_AMOUNT.getMessage(), price)); + } + + private static void printBadge(Badge badge){ + System.out.println(String.format(OutputMessage.PROMOTION_BADGE.getMessage(), + BenefitsView.badgeOutputStatement(badge))); + } + +}
Java
์˜ˆ์™ธ๋ฅผ ์ง์ ‘ ๋ฐ›๋Š” ๊ฒƒ๋ณด๋‹ค ์˜ˆ์™ธ๋ฅผ ๋˜์ง€๋Š” ์ชฝ์—์„œ e.getMessage() ๋กœ String ๊ฐ’์„ ๋˜์ ธ์ฃผ๋ฉด ๋ฉ”์„œ๋“œ๊ฐ€ ์ข€ ๋” ๋ฒ”์šฉ์„ฑ์ด ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,27 @@ +package christmas.constant; + +public enum OutputMessage { + + RESERVATION_DATE("12์›” %d์ผ์— ์šฐํ…Œ์ฝ” ์‹๋‹น์—์„œ ๋ฐ›์„ ์ด๋ฒคํŠธ ํ˜œํƒ ๋ฏธ๋ฆฌ ๋ณด๊ธฐ!"), + ORDER_MENU_PREFIX("<์ฃผ๋ฌธ ๋ฉ”๋‰ด>%n%s"), + ORDER_MENU("%s %d๊ฐœ\n"), + BEFORE_DISCOUNT_AMOUNT("<ํ• ์ธ ์ „ ์ด์ฃผ๋ฌธ ๊ธˆ์•ก>%n%,d์›\n"), + GIVEAWAY_MENU("<์ฆ์ • ๋ฉ”๋‰ด>%n%s"), + DOES_NOT_EXIST("์—†์Œ\n"), + CHAMPAGNE("์ƒดํŽ˜์ธ 1๊ฐœ\n"), + BENEFIT_DETAILS_PREFIX("<ํ˜œํƒ ๋‚ด์—ญ>%n%s"), + BENEFIT_DETAILS("%s: %,d์›\n"), + TOTAL_BENEFIT_AMOUNT("<์ดํ˜œํƒ ๊ธˆ์•ก>%n%,d์›\n"), + AFTER_DISCOUNT_AMOUNT("<ํ• ์ธ ํ›„ ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก>%n%,d์›\n"), + PROMOTION_BADGE("<12์›” ์ด๋ฒคํŠธ ๋ฐฐ์ง€>%n%s\n"); + + private final String message; + + OutputMessage(String message) { + this.message = message; + } + + public String getMessage(){ + return this.message; + } +}
Java
๊ฐœํ–‰๋ฌธ์ž๋ฅผ System.lineseparator() ๋กœ ์ฒ˜๋ฆฌํ•˜๋Š”๊ฑธ ์ถ”์ฒœ๋“œ๋ฆฝ๋‹ˆ๋‹ค! ์šด์˜์ฒด์ œ ๋ณ„๋กœ ๊ฐœํ–‰๋ฌธ์ž ํ‘œํ˜„์ด ์ƒ์ดํ•  ์ˆ˜ ์žˆ๊ฑฐ๋“ ์š”!
@@ -0,0 +1,55 @@ +package christmas.domain; + +import christmas.constant.Badge; +import christmas.constant.Menu; +import christmas.domain.promotion.ChristmasPromotion; +import java.util.Arrays; +import java.util.HashMap; + +public class BenefitStorage { + + private final long beforeDiscountAmount; + private final boolean giftMenu; + private final HashMap<ChristmasPromotion, Long> promotionResult; + + public BenefitStorage(long beforeDiscountAmount, boolean giftMenu, HashMap<ChristmasPromotion, Long> promotionResult){ + this.beforeDiscountAmount = beforeDiscountAmount; + this.giftMenu = giftMenu; + this.promotionResult = promotionResult; + } + + public long totalBenefitAmount() { + return promotionResult.values().stream().mapToLong(Long::longValue).sum(); + } + + public long afterDiscountAmount() { + long totalBenefit = totalBenefitAmount(); + + if (giftMenu) { + totalBenefit -= Menu.CHAMPAGNE.getPrice(); + } + + return beforeDiscountAmount - totalBenefit; + } + + public Badge determineBadge() { + long totalBenefit = totalBenefitAmount(); + + return Arrays.stream(Badge.values()) + .filter(badge -> totalBenefit >= badge.getPrize()) + .reduce((first, second) -> second) + .orElse(Badge.NONE); + } + + public long getBeforeDiscountAmount() { + return beforeDiscountAmount; + } + + public boolean isGiftMenu() { + return giftMenu; + } + + public HashMap<ChristmasPromotion, Long> getPromotionResult() { + return promotionResult; + } +}
Java
์ด ๋ถ€๋ถ„์„ Map์œผ๋กœ ์„ ์–ธํ•˜๋ฉด ๋‹คํ˜•์„ฑ์„ ์ข€ ๋” ํ™œ์šฉํ•˜์‹ค ์ˆ˜ ์žˆ์„๊ฑฐ์—์š”!
@@ -0,0 +1,26 @@ +package christmas.domain.promotion; + +import christmas.constant.PromotionItem; +import christmas.constant.PromotionType; +import java.util.List; + +public abstract class ChristmasPromotion { + + protected List<Integer> period; + protected PromotionItem targetItems; + protected long discountAmount; + protected PromotionType promotionType; + + public long getDiscountAmount() { + return discountAmount; + } + + public PromotionType getPromotionType(){ + return promotionType; + } + + public abstract long applyPromotion(int data, long orderAmount); + protected abstract boolean isApplicable(int date); + protected abstract boolean isEligibleForPromotion(long orderAmount); + +}
Java
์ด ๋ถ€๋ถ„์„ ์ถ”์ƒ ํด๋ž˜์Šค๋กœ ๊ตฌํ˜„ํ•˜์‹  ์ด์œ ๋ฅผ ์•Œ์ˆ˜์žˆ์„๊นŒ์š”?? ์ œ๊ฐ€ ์ถ”์ƒ ํด๋ž˜์Šค์— ๋Œ€ํ•ด ์ต์ˆ™ํ•˜์ง€ ์•Š์•„์„œ์š”!
@@ -0,0 +1,17 @@ +package christmas.dto; + +import christmas.constant.Badge; +import christmas.domain.promotion.ChristmasPromotion; +import java.util.HashMap; + +public record BenefitResult( + + long beforeDiscountAmount, + boolean giftMenu, + HashMap<ChristmasPromotion, Long> promotionResult, + long totalBenefitAmount, + long afterDiscountAmount, + Badge badge) +{ + +}
Java
๋ ˆ์ฝ”๋“œ๋ฅผ ํ™œ์šฉํ•˜์…จ๋„ค์š”. ์ด ๋ถ€๋ถ„์€ ๋ฉ”๋ชจํ•ด๋‘์—ˆ๋‹ค๊ฐ€ ์ €๋„ ์ ์šฉํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค! ์ข‹์€ ์ฝ”๋“œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,9 @@ +package christmas.util; + +public class Parser { + + public static int stringToInteger(String input) { + return Integer.parseInt(input); + } + +}
Java
์‚ฌ์†Œํ•œ ์ปจ๋ฒ„ํŒ…์ด๋ผ๋„ ๊ฐ์ฒด๋กœ ๋งŒ๋“ค์–ด์„œ ํ™œ์šฉํ•˜์‹ ๊ฒŒ ์ข‹๋„ค์š”!
@@ -0,0 +1,119 @@ +package christmas.validator; + +import christmas.constant.Menu; +import christmas.constant.MenuType; +import christmas.exception.ErrorCode; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class InputValidator { + + private static int START_DATE = 1; + private static int END_DATE = 31; + private static String COMMA = ","; + private static String HYPHEN = "-"; + private static int MENU_FORMAT_LENGTH = 2; + private static int MINIMUM_ORDER_COUNT = 1; + private static int MAXIMUN_ORDER_COUNT = 20; + + public static void validateVisitDate(String input){ + validateInteger(input); + validateNumberInRange(Integer.parseInt(input)); + } + + public static Map<Menu, Integer> validateMenuOrder(String input, Map<Menu, Integer> orderMenu){ + String[] orders = input.split(COMMA); + Set<Menu> uniqueMenu = new HashSet<>(); + + for (String order : orders) { + validate(order, orderMenu, uniqueMenu); + } + + validateOnlyBeverage(orderMenu); + validateMaxOrder(orderMenu); + + return orderMenu; + } + + private static void validate(String order, Map<Menu, Integer> orderMenu, Set<Menu> uniqueMenu){ + String[] parts = validateMenuOrderFormat(order.trim()); + + String menuName = parts[0]; + String quantity = parts[1]; + + Menu menu = getMenuByName(menuName); + + validateMenuFound(menu); + validateMinimumOrder(quantity); + validateDuplicateMenu(menu, uniqueMenu); + + orderMenu.put(menu, Integer.parseInt(quantity)); + } + + private static void validateInteger(String input){ + if(!input.chars().allMatch(Character::isDigit)){ + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + } + + private static void validateNumberInRange(int input){ + if(input > END_DATE || input < START_DATE) + throw new IllegalArgumentException(ErrorCode.INVALID_DATE.getMessage()); + } + + private static String[] validateMenuOrderFormat(String orders){ + String[] parts = orders.split(HYPHEN); + if (parts.length != MENU_FORMAT_LENGTH) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + return parts; + } + + private static void validateMenuFound(Menu menu){ + if(menu == null) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMinimumOrder(String quantity){ + if(!quantity.chars().allMatch(Character::isDigit)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + + if(Integer.parseInt(quantity) < MINIMUM_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateMaxOrder(Map<Menu, Integer> orderMenu){ + int orderCount = 0; + for(Menu menu: orderMenu.keySet()) { + orderCount += orderMenu.get(menu); + } + + if(orderCount > MAXIMUN_ORDER_COUNT) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + private static void validateDuplicateMenu(Menu menu, Set<Menu> uniqueMenu){ + if(!uniqueMenu.add(menu)) + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + + + private static void validateOnlyBeverage(Map<Menu, Integer> orderMenu){ + boolean allBeverages = orderMenu.keySet().stream() + .allMatch(menu -> menu.getMenuType() == MenuType.BEVERAGE); + + if (allBeverages) { + throw new IllegalArgumentException(ErrorCode.INVALID_MENU.getMessage()); + } + } + + private static Menu getMenuByName(String name) { + for (Menu menu : Menu.values()) { + if (menu.getName().equalsIgnoreCase(name)) { + return menu; + } + } + return null; + } +}
Java
์ค€๋‹˜์ด ๋ง์”€ํ•˜์‹ ๊ฒƒ ์ฒ˜๋Ÿผ Menu์˜ ์œ ๋ฌด๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฉ”์„œ๋“œ๋ฅผ ๊ตฌํ˜„ํ•˜์‹œ๊ฑฐ๋‚˜, Optional ๊ฐ์ฒด๋ฅผ ํ™œ์šฉํ•˜์‹œ๋Š”๊ฑธ ์ถ”์ฒœ๋“œ๋ฆฝ๋‹ˆ๋‹ค!
@@ -0,0 +1,44 @@ +package christmas.view; + +import christmas.constant.Badge; +import christmas.constant.OutputMessage; +import christmas.domain.promotion.ChristmasPromotion; +import java.util.HashMap; + +public class BenefitsView { + + public static String giftMenuOutputStatement(boolean giftMenu){ + if(giftMenu) + return OutputMessage.CHAMPAGNE.getMessage(); + + return OutputMessage.DOES_NOT_EXIST.getMessage(); + } + + public static String promotionResultOutputStatement(long totalBenefitAmount, HashMap<ChristmasPromotion, Long> promotionResult){ + if(totalBenefitAmount == 0) + return OutputMessage.DOES_NOT_EXIST.getMessage(); + + return findPromotionDetail(promotionResult).toString(); + } + + public static String badgeOutputStatement(Badge badge){ + if(badge == Badge.NONE) + return OutputMessage.DOES_NOT_EXIST.getMessage(); + return badge.getBadgeName(); + } + + private static StringBuilder findPromotionDetail(HashMap<ChristmasPromotion, Long> promotionResult){ + StringBuilder sb = new StringBuilder(); + for(ChristmasPromotion promotion: promotionResult.keySet()){ + long discount = promotionResult.get(promotion); + if(discount == 0) continue; + + sb.append(String.format(OutputMessage.BENEFIT_DETAILS.getMessage(), + promotion.getPromotionType().getMessage(), discount)); + } + + if(sb.isEmpty()) + return sb.append(OutputMessage.DOES_NOT_EXIST.getMessage()); + return sb; + } +}
Java
์ด ๋ถ€๋ถ„์„ ๋ณ„๋„ ๋ฉ”์„œ๋“œ๋กœ ๋นผ์„œ ์ธ๋ดํŠธ๋ฅผ ์ค„์—ฌ๋ณด๋Š”๊ฒŒ ์–ด๋–จ๊นŒ์š”?? ์ธํ…”๋ฆฌ์ œ์ด์—์„œ ํ•ด๋‹น ๋ถ€๋ถ„์„ ๋“œ๋ž˜๊ทธํ•œ ๋’ค cmd+option+m ์„ ์ž…๋ ฅํ•˜์‹œ๋ฉด ๋ฉ”์„œ๋“œ๋กœ ์ถ”์ถœํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค!