code stringlengths 41 34.3k | lang stringclasses 8
values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,43 @@
+package christmas.model
+
+import christmas.utils.Constant.CHRISTMAS_DAY
+import christmas.utils.Constant.EMPTY
+
+enum class DiscountType(val eventName: String) {
+ THE_DAY_DISCOUNT("ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ"),
+ WEEKDAY_DISCOUNT("ํ์ผ ํ ์ธ"),
+ WEEKEND_DISCOUNT("์ฃผ๋ง ํ ์ธ"),
+ SPECIAL_DISCOUNT("ํน๋ณ ํ ์ธ");
+
+ companion object {
+ private val decemberEvent = DecemberEvent()
+
+ fun requestTheDayDiscount(visitDate: Int): Int {
+ if (visitDate <= CHRISTMAS_DAY)
+ return decemberEvent.applyTheDayDiscount(visitDate)
+
+ return EMPTY
+ }
+
+ fun requestWeekdayDiscount(visitDate: Int, orderMenu: List<OrderItems>): Int {
+ if (visitDate in DecemberCalender.WEEKDAY.dates)
+ return decemberEvent.applyWeekdayDiscount(orderMenu)
+
+ return EMPTY
+ }
+
+ fun requestWeekendDiscount(visitDate: Int, orderMenu: List<OrderItems>): Int {
+ if (visitDate in DecemberCalender.WEEKEND.dates)
+ return decemberEvent.applyWeekendDiscount(orderMenu)
+
+ return EMPTY
+ }
+
+ fun requestSpecialDiscount(visitDate: Int): Int {
+ if (visitDate in DecemberCalender.SPECIAL_DAY.dates)
+ return decemberEvent.applySpecialDiscount()
+
+ return EMPTY
+ }
+ }
+}
\ No newline at end of file | Kotlin | enum class ์ companion object๋ ์ด๋ค ์ญํ ์ ํ๋์? ์ ๋ชฐ๋ผ์ ๋ฌผ์ด๋ด
๋๋ค ๐ |
@@ -0,0 +1,59 @@
+package christmas.utils
+
+object Constant {
+ /* Model */
+ const val FIRST_DAY_DISCOUNT_AMOUNT = 1_000
+ const val DAILY_DISCOUNT_AMOUNT = 100
+ const val ONE_DAY_DECREASE = 1
+ const val WEEK_DISCOUNT_AMOUNT = 2_023
+ const val CHRISTMAS_DAY_DISCOUNT_AMOUNT = 1_000
+ const val CHAMPAGNE_CONDITION_AMOUNT = 120_000
+ const val CHRISTMAS_DAY = 25
+ const val DISCOUNT_THRESHOLD = 10_000
+ const val EMPTY = 0
+ const val BADGE_STAR = "๋ณ"
+ const val BADGE_TREE = "ํธ๋ฆฌ"
+ const val BADGE_SANTA = "์ฐํ"
+ const val NONE = "์์"
+ const val STAR_MIN = 5_000
+ const val STAR_MAX = 9_999
+ const val TREE_MIN = 10_000
+ const val TREE_MAX = 19_999
+ const val SANTA_MIN = 20_000
+ const val FIRST_INDEX = 0
+ const val SECOND_INDEX = 1
+
+ /* Validate */
+ const val ORDER_ITEMS_SIZE = 2
+ const val VISIT_DATE_MIN = 1
+ const val VISIT_DATE_MAX = 31
+ const val QUANTITY_MINIMUM = 1
+ const val QUANTITY_MAXIMUM = 20
+ const val HYPHEN = "-"
+ const val COMMA = ","
+ const val NUMERIC_REGEX = "^\\d+$"
+ private const val ERROR_MESSAGE_PREFIX = "[ERROR] "
+ const val ERROR_MESSAGE_INPUT_VISIT_DATE = ERROR_MESSAGE_PREFIX + "์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."
+ const val ERROR_MESSAGE_INPUT_MENU = ERROR_MESSAGE_PREFIX + "์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."
+
+ /* InputView */
+ const val VISIT_DATE_ANNOUNCE_MESSAGE = "12์ ์ค ์๋น ์์ ๋ฐฉ๋ฌธ ๋ ์ง๋ ์ธ์ ์ธ๊ฐ์? (์ซ์๋ง ์
๋ ฅํด ์ฃผ์ธ์!)"
+ const val MENU_ANNOUNCE_MESSAGE = "์ฃผ๋ฌธํ์ค ๋ฉ๋ด๋ฅผ ๋ฉ๋ด์ ๊ฐ์๋ฅผ ์๋ ค ์ฃผ์ธ์. (e.g. ํด์ฐ๋ฌผํ์คํ-2,๋ ๋์์ธ-1,์ด์ฝ์ผ์ดํฌ-1)"
+
+ /* OutPutView */
+ private const val PRINT_ENTER = "\n"
+ const val START_PLANNER_MESSAGE = "์๋
ํ์ธ์! ์ฐํ
์ฝ ์๋น 12์ ์ด๋ฒคํธ ํ๋๋์
๋๋ค."
+ const val PREVIEW_ANNOUNCE_MESSAGE = "12์ %d์ผ์ ์ฐํ
์ฝ ์๋น์์ ๋ฐ์ ์ด๋ฒคํธ ํํ ๋ฏธ๋ฆฌ ๋ณด๊ธฐ!"
+ const val ORDER_MENU_TITLE_MESSAGE = "$PRINT_ENTER<์ฃผ๋ฌธ ๋ฉ๋ด>"
+ const val ITEMS_RESULT = "%s %d๊ฐ"
+ const val TOTAL_ORDER_SUM_TITLE_MESSAGE = "$PRINT_ENTER<ํ ์ธ ์ ์ด์ฃผ๋ฌธ ๊ธ์ก>"
+ const val TOTAL_AMOUNT_RESULT = "%,d์"
+ const val PRESENT_MENU_TITLE_MESSAGE = "$PRINT_ENTER<์ฆ์ ๋ฉ๋ด>"
+ const val PRESENT_AMOUNT = 1
+ const val BENEFIT_DETAILS_TITLE_MESSAGE = "$PRINT_ENTER<ํํ ๋ด์ญ>"
+ const val FREEBIE_EVENT_NAME = "์ฆ์ ์ด๋ฒคํธ"
+ const val BENEFIT_RESULT = "%s: -%,d์"
+ const val BENEFIT_AMOUNT_TITLE_MESSAGE = "$PRINT_ENTER<์ดํํ ๊ธ์ก>"
+ const val PAYMENT_AMOUNT_TITLE_MESSAGE = "$PRINT_ENTER<ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก>"
+ const val BADGE_TITLE_MESSAGE = "$PRINT_ENTER<12์ ์ด๋ฒคํธ ๋ฐฐ์ง>"
+}
\ No newline at end of file | Kotlin | ์ด๋ ๊ฒ๋ ์ธ ์ ์๊ตฐ์!
์ ๋ ์ด๋ฐ์์ผ๋ก ์ผ์ด์!
```
enum class ErrorMessage(private val message: String) {
ERROR_MENU_INPUT("์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."),
ERROR_INPUT_DAY("์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.");
fun getMessage(): String = "[ERROR] $message"
}
``` |
@@ -0,0 +1,10 @@
+package christmas.model
+
+data class OrderItems(
+ private val menuName: String,
+ private val quantity: Int
+) {
+ fun getMenuName(): String = menuName
+
+ fun getQuantity(): Int = quantity
+} | Kotlin | val ์ ์ธ ๋๋ฌธ์ ๋ฐ๋ก private๋ก ์ ํํ์ง ์์๋ ๊ฐ ์์ ์ด ๋ถ๊ฐ๋ฅํ ํ
๋ฐ, ํน์ private๋ก ์ ์ธํ ์ด์ ๊ฐ ๋ฐ๋ก ์์๊น์..?! |
@@ -0,0 +1,56 @@
+package christmas
+
+import christmas.model.DecemberEvent
+import christmas.model.OrderItems
+import org.junit.jupiter.api.Assertions
+import org.junit.jupiter.api.Test
+
+class DecemberEventTest {
+ private val decemberEvent: DecemberEvent = DecemberEvent()
+
+ @Test
+ fun `๋๋ฐ์ด ํ ์ธ ๊ธ์ก ํ
์คํธ`() {
+ val discountAmount = decemberEvent.applyTheDayDiscount(25)
+
+ Assertions.assertTrue(discountAmount == 3400)
+ }
+
+ @Test
+ fun `ํ์ผ ํ ์ธ ๊ธ์ก ํ
์คํธ`() {
+ val discountAmount = decemberEvent.applyWeekdayDiscount(listOf(OrderItems("์ด์ฝ์ผ์ดํฌ", 2), OrderItems("ํด์ฐ๋ฌผํ์คํ", 3)))
+
+ Assertions.assertTrue(discountAmount == 4046)
+ }
+
+ @Test
+ fun `์ฃผ๋ง ํ ์ธ ๊ธ์ก ํ
์คํธ`() {
+ val discountAmount = decemberEvent.applyWeekendDiscount(listOf(OrderItems("์ด์ฝ์ผ์ดํฌ", 2), OrderItems("ํด์ฐ๋ฌผํ์คํ", 3)))
+
+ Assertions.assertTrue(discountAmount == 6069)
+ }
+
+ @Test
+ fun `ํน๋ณ ํ ์ธ ๊ธ์ก ํ
์คํธ`() {
+ val discountAmount = decemberEvent.applySpecialDiscount()
+
+ Assertions.assertTrue(discountAmount == 1000)
+ }
+
+ @Test
+ fun `์ดํ์ธ ์ฆ์ ํ
์คํธ`() {
+ Assertions.assertTrue(decemberEvent.presentChampagne(130_000))
+ }
+
+ @Test
+ fun `๋ฐฐ์ง ๋ถ์ฌ ํ
์คํธ`() {
+ val noneBadge = decemberEvent.assignBadge(0)
+ val starBadge = decemberEvent.assignBadge(5000)
+ val treeBadge = decemberEvent.assignBadge(10000)
+ val santaBadge = decemberEvent.assignBadge(200000)
+
+ Assertions.assertTrue(noneBadge == "์์")
+ Assertions.assertTrue(starBadge == "๋ณ")
+ Assertions.assertTrue(treeBadge == "ํธ๋ฆฌ")
+ Assertions.assertTrue(santaBadge == "์ฐํ")
+ }
+}
\ No newline at end of file | Kotlin | ์ด ๋ถ๋ถ๋ decemberEvent.assignBadge๊ฐ ๋ฐ๋ณต๋๊ธฐ ๋๋ฌธ์ @ParameterizedTest๋ก ๊ฐ๋จํ ๋ง๋ค์ ์์๊ฑฐ ๊ฐ์์!!
๊ฐ์ธ์ ์ผ๋ก ์ ๋ ์ ๋ ๊ฒ ์ธ์๊ฐ ๋๊ฐ ํ์ํ ๊ฒฝ์ฐ์๋ @MethodSource๋ก ๊ฐ๋จํ ํ๋ ํธ์
๋๋ค!
[์ฌ๊ธฐ ๋งํฌ](https://ebabby.tistory.com/28) ์ฐธ๊ณ ํ์๋ฉด ๋ ๊ฑฐ ๊ฐ์์!! |
@@ -0,0 +1,82 @@
+package christmas.view
+
+import christmas.model.DiscountType
+import christmas.model.OrderItems
+import christmas.model.StoreMenu
+import christmas.utils.Constant.BADGE_TITLE_MESSAGE
+import christmas.utils.Constant.BENEFIT_AMOUNT_TITLE_MESSAGE
+import christmas.utils.Constant.BENEFIT_DETAILS_TITLE_MESSAGE
+import christmas.utils.Constant.BENEFIT_RESULT
+import christmas.utils.Constant.FREEBIE_EVENT_NAME
+import christmas.utils.Constant.EMPTY
+import christmas.utils.Constant.ITEMS_RESULT
+import christmas.utils.Constant.NONE
+import christmas.utils.Constant.ORDER_MENU_TITLE_MESSAGE
+import christmas.utils.Constant.PAYMENT_AMOUNT_TITLE_MESSAGE
+import christmas.utils.Constant.PRESENT_AMOUNT
+import christmas.utils.Constant.PRESENT_MENU_TITLE_MESSAGE
+import christmas.utils.Constant.PREVIEW_ANNOUNCE_MESSAGE
+import christmas.utils.Constant.START_PLANNER_MESSAGE
+import christmas.utils.Constant.TOTAL_AMOUNT_RESULT
+import christmas.utils.Constant.TOTAL_ORDER_SUM_TITLE_MESSAGE
+
+class OutputView {
+ fun printStartPlanner() {
+ println(START_PLANNER_MESSAGE)
+ }
+
+ fun printPreviewAnnounce(visitDate: Int) {
+ println(PREVIEW_ANNOUNCE_MESSAGE.format(visitDate))
+ }
+
+ fun printOrderMenu(orderMenu: List<OrderItems>) {
+ println(ORDER_MENU_TITLE_MESSAGE)
+ orderMenu.forEach { items ->
+ println(ITEMS_RESULT.format(items.getMenuName(), items.getQuantity()))
+ }
+ }
+
+ fun printTotalOrderPrize(totalOrderSum: Int) {
+ println(TOTAL_ORDER_SUM_TITLE_MESSAGE)
+ println(TOTAL_AMOUNT_RESULT.format(totalOrderSum))
+
+ }
+
+ fun printFreebieMenu(freebie: Boolean) {
+ println(PRESENT_MENU_TITLE_MESSAGE)
+ when {
+ freebie -> println(ITEMS_RESULT.format(StoreMenu.CHAMPAGNE.menuName, PRESENT_AMOUNT))
+ !freebie -> println(NONE)
+ }
+ }
+
+ fun printBenefitDetails(discountHistory: List<Pair<DiscountType, Int>>, freebie: Boolean) {
+ val discountHistoryExist = discountHistory.filter { it.second != EMPTY }
+
+ println(BENEFIT_DETAILS_TITLE_MESSAGE)
+ discountHistoryExist.forEach { (discountType, discountAmount) ->
+ println(BENEFIT_RESULT.format(discountType.eventName, discountAmount))
+ }
+
+ if(freebie)
+ println(BENEFIT_RESULT.format(FREEBIE_EVENT_NAME, StoreMenu.CHAMPAGNE.menuPrice))
+
+ if(discountHistoryExist.isEmpty() && !freebie)
+ println(NONE)
+ }
+
+ fun printBenefitAmount(totalBenefitAmount: Int) {
+ println(BENEFIT_AMOUNT_TITLE_MESSAGE)
+ println(TOTAL_AMOUNT_RESULT.format(EMPTY - totalBenefitAmount))
+ }
+
+ fun printPaymentAmount(totalOrderSum: Int, discountHistory: List<Pair<DiscountType, Int>>) {
+ println(PAYMENT_AMOUNT_TITLE_MESSAGE)
+ println(TOTAL_AMOUNT_RESULT.format(totalOrderSum - discountHistory.sumOf { it.second }))
+ }
+
+ fun printBadge(badge: String) {
+ println(BADGE_TITLE_MESSAGE)
+ println(badge)
+ }
+}
\ No newline at end of file | Kotlin | ์ด ๋ถ๋ถ์ else๋ฅผ ์ง์ํด์ผํ๋ค๋ ์๊ตฌ์ฌํญ๋๋ฌธ์ ๊ณ ๋ฏผ์ด ๋ง์์๋๋ฐ, ์ ๋ ๊ทธ๋๋ ์ฝ๋ฉ ์ปจ๋ฒค์
์ ์งํค๋๊ฒ ์ข์๊ฑฐ ๊ฐ์์ if else ๋ฌธ์ ์ฌ์ฉํ์ต๋๋ค! ์ด ๋ถ๋ถ์ ์ฌ๋๋ง๋ค ๊ด์ ์ด ๋ค๋ฅผ๊ฑฐ ๊ฐ์์ ๊ทธ๋ฅ ์ฐธ๊ณ ๋ง ํด์ฃผ์ธ์!!
[๊ด๋ จ ์ปจ๋ฒค์
๋งํฌ](https://kotlinlang.org/docs/coding-conventions.html#if-versus-when)์
๋๋ค!! |
@@ -0,0 +1,79 @@
+package christmas.model
+
+import christmas.utils.Constant.BADGE_SANTA
+import christmas.utils.Constant.BADGE_STAR
+import christmas.utils.Constant.BADGE_TREE
+import christmas.utils.Constant.CHAMPAGNE_CONDITION_AMOUNT
+import christmas.utils.Constant.CHRISTMAS_DAY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.DAILY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.FIRST_DAY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.EMPTY
+import christmas.utils.Constant.NONE
+import christmas.utils.Constant.ONE_DAY_DECREASE
+import christmas.utils.Constant.SANTA_MIN
+import christmas.utils.Constant.STAR_MAX
+import christmas.utils.Constant.STAR_MIN
+import christmas.utils.Constant.TREE_MAX
+import christmas.utils.Constant.TREE_MIN
+import christmas.utils.Constant.WEEK_DISCOUNT_AMOUNT
+
+class DecemberEvent {
+ fun applyTheDayDiscount(date: Int): Int {
+ val dailyDiscount = (date - ONE_DAY_DECREASE) * DAILY_DISCOUNT_AMOUNT
+
+ return FIRST_DAY_DISCOUNT_AMOUNT + dailyDiscount
+ }
+
+ fun applyWeekdayDiscount(orderMenu: List<OrderItems>): Int {
+ var dessertMenuCount = EMPTY
+
+ for (item in orderMenu) {
+ val increaseCount = increaseDessertMenuCount(item.getMenuName(), item.getQuantity())
+ dessertMenuCount += increaseCount
+ }
+
+ return dessertMenuCount * WEEK_DISCOUNT_AMOUNT
+ }
+
+ private fun increaseDessertMenuCount(menuName: String, quantity: Int): Int {
+ if (menuName == StoreMenu.CHOCO_CAKE.menuName || menuName == StoreMenu.ICE_CREAM.menuName)
+ return quantity
+
+ return EMPTY
+ }
+
+
+ fun applyWeekendDiscount(orderMenu: List<OrderItems>): Int {
+ var mainMenuCount = EMPTY
+
+ for (item in orderMenu) {
+ val increaseCount = increaseMainMenuCount(item.getMenuName(), item.getQuantity())
+ mainMenuCount += increaseCount
+ }
+
+ return mainMenuCount * WEEK_DISCOUNT_AMOUNT
+ }
+
+ private fun increaseMainMenuCount(menuName: String, quantity: Int): Int {
+ if (menuName == StoreMenu.T_BONE_STEAK.menuName || menuName == StoreMenu.BBQ_RIBS.menuName ||
+ menuName == StoreMenu.SEAFOOD_PASTA.menuName || menuName == StoreMenu.CHRISTMAS_PASTA.menuName
+ )
+ return quantity
+
+ return EMPTY
+ }
+
+ fun applySpecialDiscount(): Int = CHRISTMAS_DAY_DISCOUNT_AMOUNT
+
+ fun presentChampagne(totalOrderAmount: Int): Boolean = totalOrderAmount >= CHAMPAGNE_CONDITION_AMOUNT
+
+ fun assignBadge(benefitAmount: Int): String {
+ when {
+ benefitAmount in STAR_MIN..STAR_MAX -> return BADGE_STAR
+ benefitAmount in TREE_MIN..TREE_MAX -> return BADGE_TREE
+ benefitAmount >= SANTA_MIN -> return BADGE_SANTA
+ }
+
+ return NONE
+ }
+}
\ No newline at end of file | Kotlin | ์ผ์
,,๊ฐ๋
์ฑ์ ๋ง์ด ์ ๊ฒฝ ์ด ๋ฏธ์
์ด์๋๋ฐ ๋์น ๋ถ๋ถ์ด ์์๋ค์. ๋ง์ํด์ฃผ์ ๋ฐฉ๋ฒ๋ค๋ ELSE๋ฅผ ์ง์ํ ์ ์๋ค๋ ๊ฐ์ ํ์ ๊ณ ๋ คํด๋ณผ ์ ์์ ๊ฒ ๊ฐ์์. ์ง๊ธ ๋๋ ์๊ฐ์ ๋ฉ์ธ ๋ฉ๋ด๋ค์ ๋งต์ด๋ ๋ฆฌ์คํธ๋ก ๊ทธ๋ฃนํํ๊ณ ์กฐ๊ฑด ๊ฒ์ฌ๋ฅผ ์งํํ๋ค๋ฉด ํ๋ฒ์ ๊ฒ์ฌ๋ก๋ ์ถฉ๋ถํ ๋์ผํ ์ฒ๋ฆฌ๋ฅผ ํ์ ์ ์์ ๊ฑฐ ๊ฐ์์..๋ค๋ฅธ ํด๋์ค์์๋ ๋์ผํ ๋ฐฉ๋ฒ์ผ๋ก ๋ฆฌํฉํ ๋ง์ ์งํํ๊ธฐ ๋๋ฌธ์ ์์ฌ์์ด ๋ง์ด ๋จ๋ ๋ถ๋ถ์ด๋ค์..๋ฆฌ๋ทฐ ๊ฐ์ฌํฉ๋๋ค :) |
@@ -0,0 +1,59 @@
+package christmas.utils
+
+object Constant {
+ /* Model */
+ const val FIRST_DAY_DISCOUNT_AMOUNT = 1_000
+ const val DAILY_DISCOUNT_AMOUNT = 100
+ const val ONE_DAY_DECREASE = 1
+ const val WEEK_DISCOUNT_AMOUNT = 2_023
+ const val CHRISTMAS_DAY_DISCOUNT_AMOUNT = 1_000
+ const val CHAMPAGNE_CONDITION_AMOUNT = 120_000
+ const val CHRISTMAS_DAY = 25
+ const val DISCOUNT_THRESHOLD = 10_000
+ const val EMPTY = 0
+ const val BADGE_STAR = "๋ณ"
+ const val BADGE_TREE = "ํธ๋ฆฌ"
+ const val BADGE_SANTA = "์ฐํ"
+ const val NONE = "์์"
+ const val STAR_MIN = 5_000
+ const val STAR_MAX = 9_999
+ const val TREE_MIN = 10_000
+ const val TREE_MAX = 19_999
+ const val SANTA_MIN = 20_000
+ const val FIRST_INDEX = 0
+ const val SECOND_INDEX = 1
+
+ /* Validate */
+ const val ORDER_ITEMS_SIZE = 2
+ const val VISIT_DATE_MIN = 1
+ const val VISIT_DATE_MAX = 31
+ const val QUANTITY_MINIMUM = 1
+ const val QUANTITY_MAXIMUM = 20
+ const val HYPHEN = "-"
+ const val COMMA = ","
+ const val NUMERIC_REGEX = "^\\d+$"
+ private const val ERROR_MESSAGE_PREFIX = "[ERROR] "
+ const val ERROR_MESSAGE_INPUT_VISIT_DATE = ERROR_MESSAGE_PREFIX + "์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."
+ const val ERROR_MESSAGE_INPUT_MENU = ERROR_MESSAGE_PREFIX + "์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."
+
+ /* InputView */
+ const val VISIT_DATE_ANNOUNCE_MESSAGE = "12์ ์ค ์๋น ์์ ๋ฐฉ๋ฌธ ๋ ์ง๋ ์ธ์ ์ธ๊ฐ์? (์ซ์๋ง ์
๋ ฅํด ์ฃผ์ธ์!)"
+ const val MENU_ANNOUNCE_MESSAGE = "์ฃผ๋ฌธํ์ค ๋ฉ๋ด๋ฅผ ๋ฉ๋ด์ ๊ฐ์๋ฅผ ์๋ ค ์ฃผ์ธ์. (e.g. ํด์ฐ๋ฌผํ์คํ-2,๋ ๋์์ธ-1,์ด์ฝ์ผ์ดํฌ-1)"
+
+ /* OutPutView */
+ private const val PRINT_ENTER = "\n"
+ const val START_PLANNER_MESSAGE = "์๋
ํ์ธ์! ์ฐํ
์ฝ ์๋น 12์ ์ด๋ฒคํธ ํ๋๋์
๋๋ค."
+ const val PREVIEW_ANNOUNCE_MESSAGE = "12์ %d์ผ์ ์ฐํ
์ฝ ์๋น์์ ๋ฐ์ ์ด๋ฒคํธ ํํ ๋ฏธ๋ฆฌ ๋ณด๊ธฐ!"
+ const val ORDER_MENU_TITLE_MESSAGE = "$PRINT_ENTER<์ฃผ๋ฌธ ๋ฉ๋ด>"
+ const val ITEMS_RESULT = "%s %d๊ฐ"
+ const val TOTAL_ORDER_SUM_TITLE_MESSAGE = "$PRINT_ENTER<ํ ์ธ ์ ์ด์ฃผ๋ฌธ ๊ธ์ก>"
+ const val TOTAL_AMOUNT_RESULT = "%,d์"
+ const val PRESENT_MENU_TITLE_MESSAGE = "$PRINT_ENTER<์ฆ์ ๋ฉ๋ด>"
+ const val PRESENT_AMOUNT = 1
+ const val BENEFIT_DETAILS_TITLE_MESSAGE = "$PRINT_ENTER<ํํ ๋ด์ญ>"
+ const val FREEBIE_EVENT_NAME = "์ฆ์ ์ด๋ฒคํธ"
+ const val BENEFIT_RESULT = "%s: -%,d์"
+ const val BENEFIT_AMOUNT_TITLE_MESSAGE = "$PRINT_ENTER<์ดํํ ๊ธ์ก>"
+ const val PAYMENT_AMOUNT_TITLE_MESSAGE = "$PRINT_ENTER<ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก>"
+ const val BADGE_TITLE_MESSAGE = "$PRINT_ENTER<12์ ์ด๋ฒคํธ ๋ฐฐ์ง>"
+}
\ No newline at end of file | Kotlin | ์คํ ๋ณด๋ค๋ ์ฌ๋ฌ ๊ฐ์ง๊ฐ ํ์๋ ์ ์๋ ์๋ฌ ๋ฉ์ธ์ง๋ฅผ ๊ด๋ฆฌํ๊ธฐ ์ํ ์๋์ ์์ฑํ์๋ ๊ฒ ๊ฐ์์. ๋ค์ ๋ฆฌ๋ทฐ์ cbj0010๋์ด ๊ด๋ จํ์ฌ ์ ์ํด์ฃผ์ Enum Class๋ฅผ ํตํด ๊ด๋ฆฌํ๋ ๋ฐฉ๋ฒ๋ ์์ด์ park-yina๋๊ป๋ ๊ณต์ ๋๋ฆฝ๋๋ค!
```
enum class ErrorMessage(private val message: String) {
ERROR_MENU_INPUT("์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."),
ERROR_INPUT_DAY("์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.");
fun getMessage(): String = "[ERROR] $message"
}
``` |
@@ -0,0 +1,58 @@
+package christmas.controller
+
+import christmas.model.Customer
+import christmas.model.EventHelper
+import christmas.model.OrderItems
+import christmas.model.StoreMenu.Companion.sortOrderMenu
+import christmas.model.StoreMenu.Companion.splitOrderMenu
+import christmas.model.StoreMenu.Companion.splitOrderMenuForValidate
+import christmas.utils.Validate.validateOrderMenu
+import christmas.utils.Validate.validateVisitDate
+import christmas.view.InputView
+import christmas.view.OutputView
+
+class ChristmasController {
+ private val input = InputView()
+ private val output = OutputView()
+
+ fun run() {
+ output.printStartPlanner()
+ val customer = Customer(inputVisitDate(), inputOrderMenu())
+
+ customer.requestApplyDecemberEvent()
+ previewBenefit(customer, customer.getEventHelper())
+ }
+
+ private fun inputVisitDate(): Int {
+ return try {
+ val visitDateInput = input.readVisitDate()
+ validateVisitDate(visitDateInput)
+ visitDateInput.toInt()
+ } catch (e: IllegalArgumentException) {
+ println(e.message)
+ inputVisitDate()
+ }
+ }
+
+ private fun inputOrderMenu(): List<OrderItems> {
+ return try {
+ val orderMenuInput = input.readOrderMenu()
+ validateOrderMenu(splitOrderMenuForValidate(orderMenuInput))
+ splitOrderMenu(orderMenuInput)
+ } catch (e: IllegalArgumentException) {
+ println(e.message)
+ inputOrderMenu()
+ }
+ }
+
+ private fun previewBenefit(customer: Customer, eventHelper: EventHelper) {
+ output.printPreviewAnnounce(customer.getVisitDate())
+ output.printOrderMenu(sortOrderMenu(customer.getOrderMenu()))
+ output.printTotalOrderPrize(customer.calculateTotalOrderSum())
+ output.printFreebieMenu(eventHelper.getFreebie())
+ output.printBenefitDetails(eventHelper.getDiscountHistory(), eventHelper.getFreebie())
+ output.printBenefitAmount(eventHelper.calculateTotalBenefitAmount())
+ output.printPaymentAmount(customer.calculateTotalOrderSum(), eventHelper.getDiscountHistory())
+ output.printBadge(eventHelper.getBadge())
+ }
+}
\ No newline at end of file | Kotlin | validateVisitDate(visitDateInput) ์์ธ ์ฒ๋ฆฌ ๊ณผ์ ์์ IllegalArgumentException์ด ๋ฐ์ํ์ง ์๋๋ค๋ฉด ์
๋ ฅ์ด ์ ํจํ ๊ฒ์ด๊ธฐ ๋๋ฌธ์ ๋ฐ๋ก ๋ณ์๋ฅผ ์ ์ธํ์ฌ ๋ถํ์ํ ๋ฉ๋ชจ๋ฆฌ ํ ๋น์ ํ์ง ์๊ณ Int๋ก๋ง ๋ณํํ์ฌ return ํด๋ ๋ ๊ฒ์ด๋ผ๊ณ ์๊ฐํ๊ณ ์์ฑํ๋ ์ฝ๋์ธ ๊ฒ ๊ฐ์ต๋๋ค. validateVisitDate() ํจ์๋ ์์ธ ์ฒ๋ฆฌ์ ๊ดํ ํจ์์ด๊ธฐ ๋๋ฌธ์ ์ญํ ๊ณผ ์ฑ
์์ ๋ํด์๋ ๊ณ ๋ฏผํ๊ณ ์์ฑํ๋ ๊ฒ ๊ฐ๊ธด ํ์ง๋ง ์ ์ํด์ฃผ์ ์๊ฒฌ๋๋ก validateVisitDate()์ return type์ ์ง์ ํ์ฌ์ return ๊ฐ์ ๊ฐ์ง๋ ๊ฒ๋ ํ๋์ ๋ฐฉ๋ฒ์ด ๋ ์ ์์ ๊ฒ ๊ฐ์์! ๊ฐ์ฌํฉ๋๋ค :) |
@@ -0,0 +1,79 @@
+package christmas.model
+
+import christmas.utils.Constant.BADGE_SANTA
+import christmas.utils.Constant.BADGE_STAR
+import christmas.utils.Constant.BADGE_TREE
+import christmas.utils.Constant.CHAMPAGNE_CONDITION_AMOUNT
+import christmas.utils.Constant.CHRISTMAS_DAY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.DAILY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.FIRST_DAY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.EMPTY
+import christmas.utils.Constant.NONE
+import christmas.utils.Constant.ONE_DAY_DECREASE
+import christmas.utils.Constant.SANTA_MIN
+import christmas.utils.Constant.STAR_MAX
+import christmas.utils.Constant.STAR_MIN
+import christmas.utils.Constant.TREE_MAX
+import christmas.utils.Constant.TREE_MIN
+import christmas.utils.Constant.WEEK_DISCOUNT_AMOUNT
+
+class DecemberEvent {
+ fun applyTheDayDiscount(date: Int): Int {
+ val dailyDiscount = (date - ONE_DAY_DECREASE) * DAILY_DISCOUNT_AMOUNT
+
+ return FIRST_DAY_DISCOUNT_AMOUNT + dailyDiscount
+ }
+
+ fun applyWeekdayDiscount(orderMenu: List<OrderItems>): Int {
+ var dessertMenuCount = EMPTY
+
+ for (item in orderMenu) {
+ val increaseCount = increaseDessertMenuCount(item.getMenuName(), item.getQuantity())
+ dessertMenuCount += increaseCount
+ }
+
+ return dessertMenuCount * WEEK_DISCOUNT_AMOUNT
+ }
+
+ private fun increaseDessertMenuCount(menuName: String, quantity: Int): Int {
+ if (menuName == StoreMenu.CHOCO_CAKE.menuName || menuName == StoreMenu.ICE_CREAM.menuName)
+ return quantity
+
+ return EMPTY
+ }
+
+
+ fun applyWeekendDiscount(orderMenu: List<OrderItems>): Int {
+ var mainMenuCount = EMPTY
+
+ for (item in orderMenu) {
+ val increaseCount = increaseMainMenuCount(item.getMenuName(), item.getQuantity())
+ mainMenuCount += increaseCount
+ }
+
+ return mainMenuCount * WEEK_DISCOUNT_AMOUNT
+ }
+
+ private fun increaseMainMenuCount(menuName: String, quantity: Int): Int {
+ if (menuName == StoreMenu.T_BONE_STEAK.menuName || menuName == StoreMenu.BBQ_RIBS.menuName ||
+ menuName == StoreMenu.SEAFOOD_PASTA.menuName || menuName == StoreMenu.CHRISTMAS_PASTA.menuName
+ )
+ return quantity
+
+ return EMPTY
+ }
+
+ fun applySpecialDiscount(): Int = CHRISTMAS_DAY_DISCOUNT_AMOUNT
+
+ fun presentChampagne(totalOrderAmount: Int): Boolean = totalOrderAmount >= CHAMPAGNE_CONDITION_AMOUNT
+
+ fun assignBadge(benefitAmount: Int): String {
+ when {
+ benefitAmount in STAR_MIN..STAR_MAX -> return BADGE_STAR
+ benefitAmount in TREE_MIN..TREE_MAX -> return BADGE_TREE
+ benefitAmount >= SANTA_MIN -> return BADGE_SANTA
+ }
+
+ return NONE
+ }
+}
\ No newline at end of file | Kotlin | ๋ง์ฝ์ ์ ๊ฐ kotlin api๋ฅผ ํ์ฉํ ํด๋น ๋ฉ์๋๋ฅผ ๊ตฌํํ๋ค๋ฉด,
```
dessertMenuCount = orderMenu.filter { it.menuName == StoreMenu.CHOCO_CAKE.menuName || it.menuName == StoreMenu.ICE_CREAM.menuName }.sumOf { it.quantity }
```
์ด๋ ๊ฒ ํ๋ฉด ๋ฉ์๋ ํ๋๋ก ๋์ ํธ ๋ฉ๋ด ๊ฐ์๋ฅผ ๊ตฌํ ์๋ ์์ด์!! |
@@ -0,0 +1,79 @@
+package christmas.model
+
+import christmas.utils.Constant.BADGE_SANTA
+import christmas.utils.Constant.BADGE_STAR
+import christmas.utils.Constant.BADGE_TREE
+import christmas.utils.Constant.CHAMPAGNE_CONDITION_AMOUNT
+import christmas.utils.Constant.CHRISTMAS_DAY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.DAILY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.FIRST_DAY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.EMPTY
+import christmas.utils.Constant.NONE
+import christmas.utils.Constant.ONE_DAY_DECREASE
+import christmas.utils.Constant.SANTA_MIN
+import christmas.utils.Constant.STAR_MAX
+import christmas.utils.Constant.STAR_MIN
+import christmas.utils.Constant.TREE_MAX
+import christmas.utils.Constant.TREE_MIN
+import christmas.utils.Constant.WEEK_DISCOUNT_AMOUNT
+
+class DecemberEvent {
+ fun applyTheDayDiscount(date: Int): Int {
+ val dailyDiscount = (date - ONE_DAY_DECREASE) * DAILY_DISCOUNT_AMOUNT
+
+ return FIRST_DAY_DISCOUNT_AMOUNT + dailyDiscount
+ }
+
+ fun applyWeekdayDiscount(orderMenu: List<OrderItems>): Int {
+ var dessertMenuCount = EMPTY
+
+ for (item in orderMenu) {
+ val increaseCount = increaseDessertMenuCount(item.getMenuName(), item.getQuantity())
+ dessertMenuCount += increaseCount
+ }
+
+ return dessertMenuCount * WEEK_DISCOUNT_AMOUNT
+ }
+
+ private fun increaseDessertMenuCount(menuName: String, quantity: Int): Int {
+ if (menuName == StoreMenu.CHOCO_CAKE.menuName || menuName == StoreMenu.ICE_CREAM.menuName)
+ return quantity
+
+ return EMPTY
+ }
+
+
+ fun applyWeekendDiscount(orderMenu: List<OrderItems>): Int {
+ var mainMenuCount = EMPTY
+
+ for (item in orderMenu) {
+ val increaseCount = increaseMainMenuCount(item.getMenuName(), item.getQuantity())
+ mainMenuCount += increaseCount
+ }
+
+ return mainMenuCount * WEEK_DISCOUNT_AMOUNT
+ }
+
+ private fun increaseMainMenuCount(menuName: String, quantity: Int): Int {
+ if (menuName == StoreMenu.T_BONE_STEAK.menuName || menuName == StoreMenu.BBQ_RIBS.menuName ||
+ menuName == StoreMenu.SEAFOOD_PASTA.menuName || menuName == StoreMenu.CHRISTMAS_PASTA.menuName
+ )
+ return quantity
+
+ return EMPTY
+ }
+
+ fun applySpecialDiscount(): Int = CHRISTMAS_DAY_DISCOUNT_AMOUNT
+
+ fun presentChampagne(totalOrderAmount: Int): Boolean = totalOrderAmount >= CHAMPAGNE_CONDITION_AMOUNT
+
+ fun assignBadge(benefitAmount: Int): String {
+ when {
+ benefitAmount in STAR_MIN..STAR_MAX -> return BADGE_STAR
+ benefitAmount in TREE_MIN..TREE_MAX -> return BADGE_TREE
+ benefitAmount >= SANTA_MIN -> return BADGE_SANTA
+ }
+
+ return NONE
+ }
+}
\ No newline at end of file | Kotlin | ์ด๋ ๊ฒ ์กฐ๊ฑด์ด ๋ง์ ๊ฒฝ์ฐ์๋,
```
val mainMenus = listOf(StoreMenu.T_BONE_STEAK.menuName....)
if (mainMenus.contains(menu)) {
return quantity
}
```
์ด๋ ๊ฒ ํ๋ฉด ์ข๋ ๊ฐ๋จํ ์์ฑํ ์ ์์ด์!! |
@@ -0,0 +1,79 @@
+package christmas.model
+
+import christmas.utils.Constant.BADGE_SANTA
+import christmas.utils.Constant.BADGE_STAR
+import christmas.utils.Constant.BADGE_TREE
+import christmas.utils.Constant.CHAMPAGNE_CONDITION_AMOUNT
+import christmas.utils.Constant.CHRISTMAS_DAY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.DAILY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.FIRST_DAY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.EMPTY
+import christmas.utils.Constant.NONE
+import christmas.utils.Constant.ONE_DAY_DECREASE
+import christmas.utils.Constant.SANTA_MIN
+import christmas.utils.Constant.STAR_MAX
+import christmas.utils.Constant.STAR_MIN
+import christmas.utils.Constant.TREE_MAX
+import christmas.utils.Constant.TREE_MIN
+import christmas.utils.Constant.WEEK_DISCOUNT_AMOUNT
+
+class DecemberEvent {
+ fun applyTheDayDiscount(date: Int): Int {
+ val dailyDiscount = (date - ONE_DAY_DECREASE) * DAILY_DISCOUNT_AMOUNT
+
+ return FIRST_DAY_DISCOUNT_AMOUNT + dailyDiscount
+ }
+
+ fun applyWeekdayDiscount(orderMenu: List<OrderItems>): Int {
+ var dessertMenuCount = EMPTY
+
+ for (item in orderMenu) {
+ val increaseCount = increaseDessertMenuCount(item.getMenuName(), item.getQuantity())
+ dessertMenuCount += increaseCount
+ }
+
+ return dessertMenuCount * WEEK_DISCOUNT_AMOUNT
+ }
+
+ private fun increaseDessertMenuCount(menuName: String, quantity: Int): Int {
+ if (menuName == StoreMenu.CHOCO_CAKE.menuName || menuName == StoreMenu.ICE_CREAM.menuName)
+ return quantity
+
+ return EMPTY
+ }
+
+
+ fun applyWeekendDiscount(orderMenu: List<OrderItems>): Int {
+ var mainMenuCount = EMPTY
+
+ for (item in orderMenu) {
+ val increaseCount = increaseMainMenuCount(item.getMenuName(), item.getQuantity())
+ mainMenuCount += increaseCount
+ }
+
+ return mainMenuCount * WEEK_DISCOUNT_AMOUNT
+ }
+
+ private fun increaseMainMenuCount(menuName: String, quantity: Int): Int {
+ if (menuName == StoreMenu.T_BONE_STEAK.menuName || menuName == StoreMenu.BBQ_RIBS.menuName ||
+ menuName == StoreMenu.SEAFOOD_PASTA.menuName || menuName == StoreMenu.CHRISTMAS_PASTA.menuName
+ )
+ return quantity
+
+ return EMPTY
+ }
+
+ fun applySpecialDiscount(): Int = CHRISTMAS_DAY_DISCOUNT_AMOUNT
+
+ fun presentChampagne(totalOrderAmount: Int): Boolean = totalOrderAmount >= CHAMPAGNE_CONDITION_AMOUNT
+
+ fun assignBadge(benefitAmount: Int): String {
+ when {
+ benefitAmount in STAR_MIN..STAR_MAX -> return BADGE_STAR
+ benefitAmount in TREE_MIN..TREE_MAX -> return BADGE_TREE
+ benefitAmount >= SANTA_MIN -> return BADGE_SANTA
+ }
+
+ return NONE
+ }
+}
\ No newline at end of file | Kotlin | ์๋ง ์ด๋ ๊ฒ ์์ฑํ์ ์ด์ ๊ฐ, ๊ทธ๋ฅ >= ๊ธฐํธ๋ง ์ฌ์ฉํ๋ฉด STAR ๋ฐฐ์ง๋ง return ๋์ด์ ๊ทธ๋ฐ๊ฑฐ ๊ฐ์๋ฐ,
```
when {
benefitAmount >= 20000 -> retrun BADGE_SANTA
benefitAmount >= 10000 -> retrun BADGE_TREE
benefitAmount >= 5000 -> retrun BADGE_STAR
}
```
์ด๋ ๊ฒ ๊ฑฐ๊พธ๋ก ์์ฑํ๋ฉด ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ์ ์์ต๋๋ค! |
@@ -0,0 +1,79 @@
+package christmas.model
+
+import christmas.utils.Constant.BADGE_SANTA
+import christmas.utils.Constant.BADGE_STAR
+import christmas.utils.Constant.BADGE_TREE
+import christmas.utils.Constant.CHAMPAGNE_CONDITION_AMOUNT
+import christmas.utils.Constant.CHRISTMAS_DAY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.DAILY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.FIRST_DAY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.EMPTY
+import christmas.utils.Constant.NONE
+import christmas.utils.Constant.ONE_DAY_DECREASE
+import christmas.utils.Constant.SANTA_MIN
+import christmas.utils.Constant.STAR_MAX
+import christmas.utils.Constant.STAR_MIN
+import christmas.utils.Constant.TREE_MAX
+import christmas.utils.Constant.TREE_MIN
+import christmas.utils.Constant.WEEK_DISCOUNT_AMOUNT
+
+class DecemberEvent {
+ fun applyTheDayDiscount(date: Int): Int {
+ val dailyDiscount = (date - ONE_DAY_DECREASE) * DAILY_DISCOUNT_AMOUNT
+
+ return FIRST_DAY_DISCOUNT_AMOUNT + dailyDiscount
+ }
+
+ fun applyWeekdayDiscount(orderMenu: List<OrderItems>): Int {
+ var dessertMenuCount = EMPTY
+
+ for (item in orderMenu) {
+ val increaseCount = increaseDessertMenuCount(item.getMenuName(), item.getQuantity())
+ dessertMenuCount += increaseCount
+ }
+
+ return dessertMenuCount * WEEK_DISCOUNT_AMOUNT
+ }
+
+ private fun increaseDessertMenuCount(menuName: String, quantity: Int): Int {
+ if (menuName == StoreMenu.CHOCO_CAKE.menuName || menuName == StoreMenu.ICE_CREAM.menuName)
+ return quantity
+
+ return EMPTY
+ }
+
+
+ fun applyWeekendDiscount(orderMenu: List<OrderItems>): Int {
+ var mainMenuCount = EMPTY
+
+ for (item in orderMenu) {
+ val increaseCount = increaseMainMenuCount(item.getMenuName(), item.getQuantity())
+ mainMenuCount += increaseCount
+ }
+
+ return mainMenuCount * WEEK_DISCOUNT_AMOUNT
+ }
+
+ private fun increaseMainMenuCount(menuName: String, quantity: Int): Int {
+ if (menuName == StoreMenu.T_BONE_STEAK.menuName || menuName == StoreMenu.BBQ_RIBS.menuName ||
+ menuName == StoreMenu.SEAFOOD_PASTA.menuName || menuName == StoreMenu.CHRISTMAS_PASTA.menuName
+ )
+ return quantity
+
+ return EMPTY
+ }
+
+ fun applySpecialDiscount(): Int = CHRISTMAS_DAY_DISCOUNT_AMOUNT
+
+ fun presentChampagne(totalOrderAmount: Int): Boolean = totalOrderAmount >= CHAMPAGNE_CONDITION_AMOUNT
+
+ fun assignBadge(benefitAmount: Int): String {
+ when {
+ benefitAmount in STAR_MIN..STAR_MAX -> return BADGE_STAR
+ benefitAmount in TREE_MIN..TREE_MAX -> return BADGE_TREE
+ benefitAmount >= SANTA_MIN -> return BADGE_SANTA
+ }
+
+ return NONE
+ }
+}
\ No newline at end of file | Kotlin | ๋ฏธ์
์ ์๊ตฌ ์ฌํญ์ 'else๋ฅผ ์ง์ํ๋ค.'๋ ์ฌํญ์ ๋ํด์ ๊ฐ๋
์ฑ์ ์ ์งํจ๊ณผ ๋์์ else๋ฅผ ์ฌ์ฉํ์ง ์๋ ๋ฐฉ๋ฒ์ ๋ํ์ฌ ๊ณ ๋ฏผํ๊ณ ์์ฑํ๋ ์ฝ๋์ธ ๊ฒ ๊ฐ์ต๋๋ค. ์ ์ํด์ฃผ์ return when๋ ๊ตฌํ ๊ณผ์ ์์ ๊ณ ๋ คํ์์ง๋ง ์ต์ข
์ ์ผ๋ก๋ when์ ์ฌ์ฉํ๊ฒ ๋์๋ ๊ฒ ๊ฐ์์. else๋ฅผ ์ง์ํ๋ฉด์ ๋ ๋์ ๊ฐ๋
์ฑ์ ๊ฐ์ถ ์ ์๋ ๋ฐฉ๋ฒ์ ๋ ๊ณ ๋ฏผํด๋ด์ผ ๋ ๊ฒ ๊ฐ์ต๋๋ค! ๋ฆฌ๋ทฐ ๊ฐ์ฌํฉ๋๋ค :) |
@@ -0,0 +1,59 @@
+package christmas.utils
+
+object Constant {
+ /* Model */
+ const val FIRST_DAY_DISCOUNT_AMOUNT = 1_000
+ const val DAILY_DISCOUNT_AMOUNT = 100
+ const val ONE_DAY_DECREASE = 1
+ const val WEEK_DISCOUNT_AMOUNT = 2_023
+ const val CHRISTMAS_DAY_DISCOUNT_AMOUNT = 1_000
+ const val CHAMPAGNE_CONDITION_AMOUNT = 120_000
+ const val CHRISTMAS_DAY = 25
+ const val DISCOUNT_THRESHOLD = 10_000
+ const val EMPTY = 0
+ const val BADGE_STAR = "๋ณ"
+ const val BADGE_TREE = "ํธ๋ฆฌ"
+ const val BADGE_SANTA = "์ฐํ"
+ const val NONE = "์์"
+ const val STAR_MIN = 5_000
+ const val STAR_MAX = 9_999
+ const val TREE_MIN = 10_000
+ const val TREE_MAX = 19_999
+ const val SANTA_MIN = 20_000
+ const val FIRST_INDEX = 0
+ const val SECOND_INDEX = 1
+
+ /* Validate */
+ const val ORDER_ITEMS_SIZE = 2
+ const val VISIT_DATE_MIN = 1
+ const val VISIT_DATE_MAX = 31
+ const val QUANTITY_MINIMUM = 1
+ const val QUANTITY_MAXIMUM = 20
+ const val HYPHEN = "-"
+ const val COMMA = ","
+ const val NUMERIC_REGEX = "^\\d+$"
+ private const val ERROR_MESSAGE_PREFIX = "[ERROR] "
+ const val ERROR_MESSAGE_INPUT_VISIT_DATE = ERROR_MESSAGE_PREFIX + "์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."
+ const val ERROR_MESSAGE_INPUT_MENU = ERROR_MESSAGE_PREFIX + "์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."
+
+ /* InputView */
+ const val VISIT_DATE_ANNOUNCE_MESSAGE = "12์ ์ค ์๋น ์์ ๋ฐฉ๋ฌธ ๋ ์ง๋ ์ธ์ ์ธ๊ฐ์? (์ซ์๋ง ์
๋ ฅํด ์ฃผ์ธ์!)"
+ const val MENU_ANNOUNCE_MESSAGE = "์ฃผ๋ฌธํ์ค ๋ฉ๋ด๋ฅผ ๋ฉ๋ด์ ๊ฐ์๋ฅผ ์๋ ค ์ฃผ์ธ์. (e.g. ํด์ฐ๋ฌผํ์คํ-2,๋ ๋์์ธ-1,์ด์ฝ์ผ์ดํฌ-1)"
+
+ /* OutPutView */
+ private const val PRINT_ENTER = "\n"
+ const val START_PLANNER_MESSAGE = "์๋
ํ์ธ์! ์ฐํ
์ฝ ์๋น 12์ ์ด๋ฒคํธ ํ๋๋์
๋๋ค."
+ const val PREVIEW_ANNOUNCE_MESSAGE = "12์ %d์ผ์ ์ฐํ
์ฝ ์๋น์์ ๋ฐ์ ์ด๋ฒคํธ ํํ ๋ฏธ๋ฆฌ ๋ณด๊ธฐ!"
+ const val ORDER_MENU_TITLE_MESSAGE = "$PRINT_ENTER<์ฃผ๋ฌธ ๋ฉ๋ด>"
+ const val ITEMS_RESULT = "%s %d๊ฐ"
+ const val TOTAL_ORDER_SUM_TITLE_MESSAGE = "$PRINT_ENTER<ํ ์ธ ์ ์ด์ฃผ๋ฌธ ๊ธ์ก>"
+ const val TOTAL_AMOUNT_RESULT = "%,d์"
+ const val PRESENT_MENU_TITLE_MESSAGE = "$PRINT_ENTER<์ฆ์ ๋ฉ๋ด>"
+ const val PRESENT_AMOUNT = 1
+ const val BENEFIT_DETAILS_TITLE_MESSAGE = "$PRINT_ENTER<ํํ ๋ด์ญ>"
+ const val FREEBIE_EVENT_NAME = "์ฆ์ ์ด๋ฒคํธ"
+ const val BENEFIT_RESULT = "%s: -%,d์"
+ const val BENEFIT_AMOUNT_TITLE_MESSAGE = "$PRINT_ENTER<์ดํํ ๊ธ์ก>"
+ const val PAYMENT_AMOUNT_TITLE_MESSAGE = "$PRINT_ENTER<ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก>"
+ const val BADGE_TITLE_MESSAGE = "$PRINT_ENTER<12์ ์ด๋ฒคํธ ๋ฐฐ์ง>"
+}
\ No newline at end of file | Kotlin | ์์ฑํด์ฃผ์ ์ฝ๋๋ ๋งค์ฐ ๊น๋ํ๊ณ ๊ฐ๋
์ฑ์ด ๋์ ๋ณด์ฌ์! ์๋ฌ ๋ฉ์ธ์ง๋ค์ด ์ฐ๊ด์ฑ์ด ์๋ ์์๋ค์ด์ง๋ง Enum Class๋ ํ๋์ ๋ชจ๋ธ๋ก ๊ตฌ์ฑํ๊ธฐ ๋๋ฌธ์ ๊ฐ์ฒด๋ฅผ ์ฆ๊ฐ์ํค๊ธฐ ๋ณด๋ค๋ ๋ค์๊ณผ ๊ฐ์ด ์์ํ ์ฒ๋ฆฌ๋ง ํ์๋ ๊ฒ์ธ๋ฐ ์๋ฌ ๋ฉ์ธ์ง๋ค์ ๋ ๋ช
ํํ๊ฒ ๋ถ๋ฅํ๋ ๋ฐฉ๋ฒ์ด ์์ง ๋ง์ด ๋ถ์กฑํ ๊ฒ์ ์ฌ์ค์ธ ๊ฒ ๊ฐ์ต๋๋ค. ๊ตฌ์ฑ๊ณผ ์ค๊ณ, ๊ฐ๋
์ฑ์ ๋์ด๋ ๋ฐฉ๋ฒ์ ๋ํด ๋ ํ์ตํด๋ณด๊ฒ ์ต๋๋ค. ๋ฆฌ๋ทฐ ๊ฐ์ฌํฉ๋๋ค :) |
@@ -0,0 +1,43 @@
+package christmas.model
+
+import christmas.utils.Constant.CHRISTMAS_DAY
+import christmas.utils.Constant.EMPTY
+
+enum class DiscountType(val eventName: String) {
+ THE_DAY_DISCOUNT("ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ"),
+ WEEKDAY_DISCOUNT("ํ์ผ ํ ์ธ"),
+ WEEKEND_DISCOUNT("์ฃผ๋ง ํ ์ธ"),
+ SPECIAL_DISCOUNT("ํน๋ณ ํ ์ธ");
+
+ companion object {
+ private val decemberEvent = DecemberEvent()
+
+ fun requestTheDayDiscount(visitDate: Int): Int {
+ if (visitDate <= CHRISTMAS_DAY)
+ return decemberEvent.applyTheDayDiscount(visitDate)
+
+ return EMPTY
+ }
+
+ fun requestWeekdayDiscount(visitDate: Int, orderMenu: List<OrderItems>): Int {
+ if (visitDate in DecemberCalender.WEEKDAY.dates)
+ return decemberEvent.applyWeekdayDiscount(orderMenu)
+
+ return EMPTY
+ }
+
+ fun requestWeekendDiscount(visitDate: Int, orderMenu: List<OrderItems>): Int {
+ if (visitDate in DecemberCalender.WEEKEND.dates)
+ return decemberEvent.applyWeekendDiscount(orderMenu)
+
+ return EMPTY
+ }
+
+ fun requestSpecialDiscount(visitDate: Int): Int {
+ if (visitDate in DecemberCalender.SPECIAL_DAY.dates)
+ return decemberEvent.applySpecialDiscount()
+
+ return EMPTY
+ }
+ }
+}
\ No newline at end of file | Kotlin | ๋ต๋ณ์ ๋๋ฆฌ๊ณ ์ ๋ด์ฉ์ ์์ฑํ์๋๋ฐ..์ฝ๋ ์์ฒด์ ์ผ๋ก๋ ๋จ์ผ ์ฑ
์ ์์น์ ๊ดํด ๋ ๊ณ ๋ คํ ๋ถ๋ถ์ด ์์ด ๋ณด์ด๊ณ ํน์๋ ์ ๋ต๋ณ์ด ์ฌ์ค๊ณผ ๋ค๋ฅธ ๋ด์ฉ์ด ํฌํจ๋๋ค๋ฉด ํ์ต์ ํผ๋์ ๋๋ฆด ์ ์์ ๊ฒ ๊ฐ์ ์ ์ค๋ช
๋ ๋งํฌ๋ฅผ ์ฒจ๋ถํฉ๋๋ค! ํฐ ๋์์ ๋๋ฆฌ์ง ๋ชปํด ์ฃ์กํฉ๋๋ค..
๋งํฌ 1. https://kotlinlang.org/docs/object-declarations.html#companion-objects
๋งํฌ 2. https://www.baeldung.com/kotlin/enum-static-method |
@@ -0,0 +1,59 @@
+package christmas.utils
+
+object Constant {
+ /* Model */
+ const val FIRST_DAY_DISCOUNT_AMOUNT = 1_000
+ const val DAILY_DISCOUNT_AMOUNT = 100
+ const val ONE_DAY_DECREASE = 1
+ const val WEEK_DISCOUNT_AMOUNT = 2_023
+ const val CHRISTMAS_DAY_DISCOUNT_AMOUNT = 1_000
+ const val CHAMPAGNE_CONDITION_AMOUNT = 120_000
+ const val CHRISTMAS_DAY = 25
+ const val DISCOUNT_THRESHOLD = 10_000
+ const val EMPTY = 0
+ const val BADGE_STAR = "๋ณ"
+ const val BADGE_TREE = "ํธ๋ฆฌ"
+ const val BADGE_SANTA = "์ฐํ"
+ const val NONE = "์์"
+ const val STAR_MIN = 5_000
+ const val STAR_MAX = 9_999
+ const val TREE_MIN = 10_000
+ const val TREE_MAX = 19_999
+ const val SANTA_MIN = 20_000
+ const val FIRST_INDEX = 0
+ const val SECOND_INDEX = 1
+
+ /* Validate */
+ const val ORDER_ITEMS_SIZE = 2
+ const val VISIT_DATE_MIN = 1
+ const val VISIT_DATE_MAX = 31
+ const val QUANTITY_MINIMUM = 1
+ const val QUANTITY_MAXIMUM = 20
+ const val HYPHEN = "-"
+ const val COMMA = ","
+ const val NUMERIC_REGEX = "^\\d+$"
+ private const val ERROR_MESSAGE_PREFIX = "[ERROR] "
+ const val ERROR_MESSAGE_INPUT_VISIT_DATE = ERROR_MESSAGE_PREFIX + "์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."
+ const val ERROR_MESSAGE_INPUT_MENU = ERROR_MESSAGE_PREFIX + "์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."
+
+ /* InputView */
+ const val VISIT_DATE_ANNOUNCE_MESSAGE = "12์ ์ค ์๋น ์์ ๋ฐฉ๋ฌธ ๋ ์ง๋ ์ธ์ ์ธ๊ฐ์? (์ซ์๋ง ์
๋ ฅํด ์ฃผ์ธ์!)"
+ const val MENU_ANNOUNCE_MESSAGE = "์ฃผ๋ฌธํ์ค ๋ฉ๋ด๋ฅผ ๋ฉ๋ด์ ๊ฐ์๋ฅผ ์๋ ค ์ฃผ์ธ์. (e.g. ํด์ฐ๋ฌผํ์คํ-2,๋ ๋์์ธ-1,์ด์ฝ์ผ์ดํฌ-1)"
+
+ /* OutPutView */
+ private const val PRINT_ENTER = "\n"
+ const val START_PLANNER_MESSAGE = "์๋
ํ์ธ์! ์ฐํ
์ฝ ์๋น 12์ ์ด๋ฒคํธ ํ๋๋์
๋๋ค."
+ const val PREVIEW_ANNOUNCE_MESSAGE = "12์ %d์ผ์ ์ฐํ
์ฝ ์๋น์์ ๋ฐ์ ์ด๋ฒคํธ ํํ ๋ฏธ๋ฆฌ ๋ณด๊ธฐ!"
+ const val ORDER_MENU_TITLE_MESSAGE = "$PRINT_ENTER<์ฃผ๋ฌธ ๋ฉ๋ด>"
+ const val ITEMS_RESULT = "%s %d๊ฐ"
+ const val TOTAL_ORDER_SUM_TITLE_MESSAGE = "$PRINT_ENTER<ํ ์ธ ์ ์ด์ฃผ๋ฌธ ๊ธ์ก>"
+ const val TOTAL_AMOUNT_RESULT = "%,d์"
+ const val PRESENT_MENU_TITLE_MESSAGE = "$PRINT_ENTER<์ฆ์ ๋ฉ๋ด>"
+ const val PRESENT_AMOUNT = 1
+ const val BENEFIT_DETAILS_TITLE_MESSAGE = "$PRINT_ENTER<ํํ ๋ด์ญ>"
+ const val FREEBIE_EVENT_NAME = "์ฆ์ ์ด๋ฒคํธ"
+ const val BENEFIT_RESULT = "%s: -%,d์"
+ const val BENEFIT_AMOUNT_TITLE_MESSAGE = "$PRINT_ENTER<์ดํํ ๊ธ์ก>"
+ const val PAYMENT_AMOUNT_TITLE_MESSAGE = "$PRINT_ENTER<ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก>"
+ const val BADGE_TITLE_MESSAGE = "$PRINT_ENTER<12์ ์ด๋ฒคํธ ๋ฐฐ์ง>"
+}
\ No newline at end of file | Kotlin | ์ ์ด๋ ๊ฒ ์์ฑํ๋ค๋ฉด ์ ๋ง ๊น๋ํด์ง ๊ฒ ๊ฐ์์! ์ ํํ
๊ผญ ํ์ํ ํ์ต ๋ถ๋ถ์ด์์ต๋๋ค. ๋ค์ ์ฝ๋๋ถํฐ ์ ์ฉํด ํ์คํ ๊ฐ์ ํด๋ณด๊ฒ ์ต๋๋ค! ๋ฆฌ๋ทฐ ๊ฐ์ฌ๋๋ฆฝ๋๋ค :) |
@@ -0,0 +1,10 @@
+package christmas.model
+
+data class OrderItems(
+ private val menuName: String,
+ private val quantity: Int
+) {
+ fun getMenuName(): String = menuName
+
+ fun getQuantity(): Int = quantity
+} | Kotlin | 3์ฃผ์ฐจ ๊ณตํต ํผ๋๋ฐฑ์๋ ํฌํจ๋์ด ์๋ ๋ด์ฉ์ธ๋ฐ val์ ๊ฐ์ ๋ถ๋ณ์ผ๋ก ์ ํํ๊ณ ์ ํ๋ ์๋์ด๊ณ private์ ๊ฐ์ฒด์ ์ํ ์ ๊ทผ์ ์ ํํ๋ ์๋๋ผ๊ณ ์๊ฐํ์์ต๋๋ค! ๊ฐ์ ์์ ์ ๋ง๋ ๊ฒ๋ ์ค์ํ์ง๋ง private ์ ๊ทผ ์ ํ์ ํตํด ๊ฐ์ฒด๋ฅผ ํ์คํ๊ฒ ๋ณดํธํ๊ณ ์ ํ๋ ์๋์ ์์ฑํ๊ฒ ์ฝ๋์ธ ๊ฒ ๊ฐ์์. ๋ฆฌ๋ทฐ ๊ฐ์ฌํฉ๋๋ค :) |
@@ -0,0 +1,82 @@
+package christmas.view
+
+import christmas.model.DiscountType
+import christmas.model.OrderItems
+import christmas.model.StoreMenu
+import christmas.utils.Constant.BADGE_TITLE_MESSAGE
+import christmas.utils.Constant.BENEFIT_AMOUNT_TITLE_MESSAGE
+import christmas.utils.Constant.BENEFIT_DETAILS_TITLE_MESSAGE
+import christmas.utils.Constant.BENEFIT_RESULT
+import christmas.utils.Constant.FREEBIE_EVENT_NAME
+import christmas.utils.Constant.EMPTY
+import christmas.utils.Constant.ITEMS_RESULT
+import christmas.utils.Constant.NONE
+import christmas.utils.Constant.ORDER_MENU_TITLE_MESSAGE
+import christmas.utils.Constant.PAYMENT_AMOUNT_TITLE_MESSAGE
+import christmas.utils.Constant.PRESENT_AMOUNT
+import christmas.utils.Constant.PRESENT_MENU_TITLE_MESSAGE
+import christmas.utils.Constant.PREVIEW_ANNOUNCE_MESSAGE
+import christmas.utils.Constant.START_PLANNER_MESSAGE
+import christmas.utils.Constant.TOTAL_AMOUNT_RESULT
+import christmas.utils.Constant.TOTAL_ORDER_SUM_TITLE_MESSAGE
+
+class OutputView {
+ fun printStartPlanner() {
+ println(START_PLANNER_MESSAGE)
+ }
+
+ fun printPreviewAnnounce(visitDate: Int) {
+ println(PREVIEW_ANNOUNCE_MESSAGE.format(visitDate))
+ }
+
+ fun printOrderMenu(orderMenu: List<OrderItems>) {
+ println(ORDER_MENU_TITLE_MESSAGE)
+ orderMenu.forEach { items ->
+ println(ITEMS_RESULT.format(items.getMenuName(), items.getQuantity()))
+ }
+ }
+
+ fun printTotalOrderPrize(totalOrderSum: Int) {
+ println(TOTAL_ORDER_SUM_TITLE_MESSAGE)
+ println(TOTAL_AMOUNT_RESULT.format(totalOrderSum))
+
+ }
+
+ fun printFreebieMenu(freebie: Boolean) {
+ println(PRESENT_MENU_TITLE_MESSAGE)
+ when {
+ freebie -> println(ITEMS_RESULT.format(StoreMenu.CHAMPAGNE.menuName, PRESENT_AMOUNT))
+ !freebie -> println(NONE)
+ }
+ }
+
+ fun printBenefitDetails(discountHistory: List<Pair<DiscountType, Int>>, freebie: Boolean) {
+ val discountHistoryExist = discountHistory.filter { it.second != EMPTY }
+
+ println(BENEFIT_DETAILS_TITLE_MESSAGE)
+ discountHistoryExist.forEach { (discountType, discountAmount) ->
+ println(BENEFIT_RESULT.format(discountType.eventName, discountAmount))
+ }
+
+ if(freebie)
+ println(BENEFIT_RESULT.format(FREEBIE_EVENT_NAME, StoreMenu.CHAMPAGNE.menuPrice))
+
+ if(discountHistoryExist.isEmpty() && !freebie)
+ println(NONE)
+ }
+
+ fun printBenefitAmount(totalBenefitAmount: Int) {
+ println(BENEFIT_AMOUNT_TITLE_MESSAGE)
+ println(TOTAL_AMOUNT_RESULT.format(EMPTY - totalBenefitAmount))
+ }
+
+ fun printPaymentAmount(totalOrderSum: Int, discountHistory: List<Pair<DiscountType, Int>>) {
+ println(PAYMENT_AMOUNT_TITLE_MESSAGE)
+ println(TOTAL_AMOUNT_RESULT.format(totalOrderSum - discountHistory.sumOf { it.second }))
+ }
+
+ fun printBadge(badge: String) {
+ println(BADGE_TITLE_MESSAGE)
+ println(badge)
+ }
+}
\ No newline at end of file | Kotlin | else๋ฅผ ์ง์ํ๋ ๊ฒ์ด ๊ตฌํ ๊ณผ์ ์์ ์ฌ๋ฌ๋ฒ ๊ณ ๋ฏผ์ ๋น ์ง๊ฒ ํ๋ ๊ฒ ๊ฐ์์.. ๊ฐ๋
์ฑ์ ๋์ด๊ณ ์ปจ๋ฒค์
์ ์งํฌ ์ ์๋ค๋ฉด ๋ ์ฃผ์ฒด์ ์ผ๋ก ํ๋จํ๊ณ ์์ฑํ๋ ๊ฒ๋ ์ฌ๋ฐ๋ฅธ ๋ฐฉํฅ์ด๋ผ๊ณ ๊ณต๊ฐ์ด ๊ฐ๋ ๊ฒ ๊ฐ์์! ๋ฆฌ๋ทฐ ๊ฐ์ฌํฉ๋๋ค :) |
@@ -0,0 +1,79 @@
+package christmas.model
+
+import christmas.utils.Constant.BADGE_SANTA
+import christmas.utils.Constant.BADGE_STAR
+import christmas.utils.Constant.BADGE_TREE
+import christmas.utils.Constant.CHAMPAGNE_CONDITION_AMOUNT
+import christmas.utils.Constant.CHRISTMAS_DAY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.DAILY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.FIRST_DAY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.EMPTY
+import christmas.utils.Constant.NONE
+import christmas.utils.Constant.ONE_DAY_DECREASE
+import christmas.utils.Constant.SANTA_MIN
+import christmas.utils.Constant.STAR_MAX
+import christmas.utils.Constant.STAR_MIN
+import christmas.utils.Constant.TREE_MAX
+import christmas.utils.Constant.TREE_MIN
+import christmas.utils.Constant.WEEK_DISCOUNT_AMOUNT
+
+class DecemberEvent {
+ fun applyTheDayDiscount(date: Int): Int {
+ val dailyDiscount = (date - ONE_DAY_DECREASE) * DAILY_DISCOUNT_AMOUNT
+
+ return FIRST_DAY_DISCOUNT_AMOUNT + dailyDiscount
+ }
+
+ fun applyWeekdayDiscount(orderMenu: List<OrderItems>): Int {
+ var dessertMenuCount = EMPTY
+
+ for (item in orderMenu) {
+ val increaseCount = increaseDessertMenuCount(item.getMenuName(), item.getQuantity())
+ dessertMenuCount += increaseCount
+ }
+
+ return dessertMenuCount * WEEK_DISCOUNT_AMOUNT
+ }
+
+ private fun increaseDessertMenuCount(menuName: String, quantity: Int): Int {
+ if (menuName == StoreMenu.CHOCO_CAKE.menuName || menuName == StoreMenu.ICE_CREAM.menuName)
+ return quantity
+
+ return EMPTY
+ }
+
+
+ fun applyWeekendDiscount(orderMenu: List<OrderItems>): Int {
+ var mainMenuCount = EMPTY
+
+ for (item in orderMenu) {
+ val increaseCount = increaseMainMenuCount(item.getMenuName(), item.getQuantity())
+ mainMenuCount += increaseCount
+ }
+
+ return mainMenuCount * WEEK_DISCOUNT_AMOUNT
+ }
+
+ private fun increaseMainMenuCount(menuName: String, quantity: Int): Int {
+ if (menuName == StoreMenu.T_BONE_STEAK.menuName || menuName == StoreMenu.BBQ_RIBS.menuName ||
+ menuName == StoreMenu.SEAFOOD_PASTA.menuName || menuName == StoreMenu.CHRISTMAS_PASTA.menuName
+ )
+ return quantity
+
+ return EMPTY
+ }
+
+ fun applySpecialDiscount(): Int = CHRISTMAS_DAY_DISCOUNT_AMOUNT
+
+ fun presentChampagne(totalOrderAmount: Int): Boolean = totalOrderAmount >= CHAMPAGNE_CONDITION_AMOUNT
+
+ fun assignBadge(benefitAmount: Int): String {
+ when {
+ benefitAmount in STAR_MIN..STAR_MAX -> return BADGE_STAR
+ benefitAmount in TREE_MIN..TREE_MAX -> return BADGE_TREE
+ benefitAmount >= SANTA_MIN -> return BADGE_SANTA
+ }
+
+ return NONE
+ }
+}
\ No newline at end of file | Kotlin | ์ ์ํด์ฃผ์ ์ฝ๋๊ฐ ํ์คํ ๊ฐ๊ฒฐํ๊ณ ์ฝํ๋ฆฐ์ค๋ฌ์ ๋ณด์ด๋ค์! ์์ผ๋ก์ ๊ณผ์ ์์๋ ์ฝํ๋ฆฐ์ ๋ํ ํ์ต ์๊ฐ์ ์ผ์ ์๊ฐ ์ง์ ํด์ ์ค์ค๋ก ์๋ จ๋๋ฅผ ํฅ์์ํฌ ํ์๊ฐ ์์ ๊ฒ ๊ฐ์์. ๋ฆฌ๋ทฐ ๊ฐ์ฌํฉ๋๋ค :) |
@@ -0,0 +1,79 @@
+package christmas.model
+
+import christmas.utils.Constant.BADGE_SANTA
+import christmas.utils.Constant.BADGE_STAR
+import christmas.utils.Constant.BADGE_TREE
+import christmas.utils.Constant.CHAMPAGNE_CONDITION_AMOUNT
+import christmas.utils.Constant.CHRISTMAS_DAY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.DAILY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.FIRST_DAY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.EMPTY
+import christmas.utils.Constant.NONE
+import christmas.utils.Constant.ONE_DAY_DECREASE
+import christmas.utils.Constant.SANTA_MIN
+import christmas.utils.Constant.STAR_MAX
+import christmas.utils.Constant.STAR_MIN
+import christmas.utils.Constant.TREE_MAX
+import christmas.utils.Constant.TREE_MIN
+import christmas.utils.Constant.WEEK_DISCOUNT_AMOUNT
+
+class DecemberEvent {
+ fun applyTheDayDiscount(date: Int): Int {
+ val dailyDiscount = (date - ONE_DAY_DECREASE) * DAILY_DISCOUNT_AMOUNT
+
+ return FIRST_DAY_DISCOUNT_AMOUNT + dailyDiscount
+ }
+
+ fun applyWeekdayDiscount(orderMenu: List<OrderItems>): Int {
+ var dessertMenuCount = EMPTY
+
+ for (item in orderMenu) {
+ val increaseCount = increaseDessertMenuCount(item.getMenuName(), item.getQuantity())
+ dessertMenuCount += increaseCount
+ }
+
+ return dessertMenuCount * WEEK_DISCOUNT_AMOUNT
+ }
+
+ private fun increaseDessertMenuCount(menuName: String, quantity: Int): Int {
+ if (menuName == StoreMenu.CHOCO_CAKE.menuName || menuName == StoreMenu.ICE_CREAM.menuName)
+ return quantity
+
+ return EMPTY
+ }
+
+
+ fun applyWeekendDiscount(orderMenu: List<OrderItems>): Int {
+ var mainMenuCount = EMPTY
+
+ for (item in orderMenu) {
+ val increaseCount = increaseMainMenuCount(item.getMenuName(), item.getQuantity())
+ mainMenuCount += increaseCount
+ }
+
+ return mainMenuCount * WEEK_DISCOUNT_AMOUNT
+ }
+
+ private fun increaseMainMenuCount(menuName: String, quantity: Int): Int {
+ if (menuName == StoreMenu.T_BONE_STEAK.menuName || menuName == StoreMenu.BBQ_RIBS.menuName ||
+ menuName == StoreMenu.SEAFOOD_PASTA.menuName || menuName == StoreMenu.CHRISTMAS_PASTA.menuName
+ )
+ return quantity
+
+ return EMPTY
+ }
+
+ fun applySpecialDiscount(): Int = CHRISTMAS_DAY_DISCOUNT_AMOUNT
+
+ fun presentChampagne(totalOrderAmount: Int): Boolean = totalOrderAmount >= CHAMPAGNE_CONDITION_AMOUNT
+
+ fun assignBadge(benefitAmount: Int): String {
+ when {
+ benefitAmount in STAR_MIN..STAR_MAX -> return BADGE_STAR
+ benefitAmount in TREE_MIN..TREE_MAX -> return BADGE_TREE
+ benefitAmount >= SANTA_MIN -> return BADGE_SANTA
+ }
+
+ return NONE
+ }
+}
\ No newline at end of file | Kotlin | ์ ์ํด์ฃผ์ ์ฝ๋๊ฐ ํ์คํ ๊ฐ์ ๋ ์ฝ๋์ธ ๊ฑฐ ๊ฐ์์. ์ฌ์ค ๋ฐฉ๋ฒ์ ์๊ณ ๋ ๋ฐ๋ณต๋๋ ๋ฆฌํฉํ ๋ง ์์์ ํด๋น ๋ถ๋ถ์ ๋์ณฃ๋ค๋๊ฒ ์์ฌ์์ ๋ง์ด ๋จ๊ฒผ์ต๋๋ค.. ๊น๋ํ ์ฝ๋์ ๋ฆฌ๋ทฐ ๊ฐ์ฌํฉ๋๋ค :) |
@@ -0,0 +1,79 @@
+package christmas.model
+
+import christmas.utils.Constant.BADGE_SANTA
+import christmas.utils.Constant.BADGE_STAR
+import christmas.utils.Constant.BADGE_TREE
+import christmas.utils.Constant.CHAMPAGNE_CONDITION_AMOUNT
+import christmas.utils.Constant.CHRISTMAS_DAY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.DAILY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.FIRST_DAY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.EMPTY
+import christmas.utils.Constant.NONE
+import christmas.utils.Constant.ONE_DAY_DECREASE
+import christmas.utils.Constant.SANTA_MIN
+import christmas.utils.Constant.STAR_MAX
+import christmas.utils.Constant.STAR_MIN
+import christmas.utils.Constant.TREE_MAX
+import christmas.utils.Constant.TREE_MIN
+import christmas.utils.Constant.WEEK_DISCOUNT_AMOUNT
+
+class DecemberEvent {
+ fun applyTheDayDiscount(date: Int): Int {
+ val dailyDiscount = (date - ONE_DAY_DECREASE) * DAILY_DISCOUNT_AMOUNT
+
+ return FIRST_DAY_DISCOUNT_AMOUNT + dailyDiscount
+ }
+
+ fun applyWeekdayDiscount(orderMenu: List<OrderItems>): Int {
+ var dessertMenuCount = EMPTY
+
+ for (item in orderMenu) {
+ val increaseCount = increaseDessertMenuCount(item.getMenuName(), item.getQuantity())
+ dessertMenuCount += increaseCount
+ }
+
+ return dessertMenuCount * WEEK_DISCOUNT_AMOUNT
+ }
+
+ private fun increaseDessertMenuCount(menuName: String, quantity: Int): Int {
+ if (menuName == StoreMenu.CHOCO_CAKE.menuName || menuName == StoreMenu.ICE_CREAM.menuName)
+ return quantity
+
+ return EMPTY
+ }
+
+
+ fun applyWeekendDiscount(orderMenu: List<OrderItems>): Int {
+ var mainMenuCount = EMPTY
+
+ for (item in orderMenu) {
+ val increaseCount = increaseMainMenuCount(item.getMenuName(), item.getQuantity())
+ mainMenuCount += increaseCount
+ }
+
+ return mainMenuCount * WEEK_DISCOUNT_AMOUNT
+ }
+
+ private fun increaseMainMenuCount(menuName: String, quantity: Int): Int {
+ if (menuName == StoreMenu.T_BONE_STEAK.menuName || menuName == StoreMenu.BBQ_RIBS.menuName ||
+ menuName == StoreMenu.SEAFOOD_PASTA.menuName || menuName == StoreMenu.CHRISTMAS_PASTA.menuName
+ )
+ return quantity
+
+ return EMPTY
+ }
+
+ fun applySpecialDiscount(): Int = CHRISTMAS_DAY_DISCOUNT_AMOUNT
+
+ fun presentChampagne(totalOrderAmount: Int): Boolean = totalOrderAmount >= CHAMPAGNE_CONDITION_AMOUNT
+
+ fun assignBadge(benefitAmount: Int): String {
+ when {
+ benefitAmount in STAR_MIN..STAR_MAX -> return BADGE_STAR
+ benefitAmount in TREE_MIN..TREE_MAX -> return BADGE_TREE
+ benefitAmount >= SANTA_MIN -> return BADGE_SANTA
+ }
+
+ return NONE
+ }
+}
\ No newline at end of file | Kotlin | ์ ๋์ ์์์ ๋ฐ๋ผ์ ๋ ๋ค๋ฅด๊ฒ ์์ฑ๋ ์ ์๋ค์. ์ ์ ํด์ฃผ์ ์ฝ๋์ฒ๋ผ ๋ฎ์ ๊ธ์ก๋ณด๋ค๋ ๋์ ๊ธ์ก๋ถํฐ ๊ฒ์ฌํ๋ ๊ฒ์ด ์ฒ๋ฆฌ ๊ณผ์ ์ ํ์คํ ์ค์ผ ์ ์๊ฒ ๋ค๋ ์๊ฐ์ด ๋ค์ด์! ๋ง์ ๋ถ๋ถ์์ ๋์์ ๋ฐ๊ฒ ๋ ๊ฒ ๊ฐ์์.. ์ ๋ง ๊ฐ์ฌํฉ๋๋ค! |
@@ -0,0 +1,56 @@
+package christmas
+
+import christmas.model.DecemberEvent
+import christmas.model.OrderItems
+import org.junit.jupiter.api.Assertions
+import org.junit.jupiter.api.Test
+
+class DecemberEventTest {
+ private val decemberEvent: DecemberEvent = DecemberEvent()
+
+ @Test
+ fun `๋๋ฐ์ด ํ ์ธ ๊ธ์ก ํ
์คํธ`() {
+ val discountAmount = decemberEvent.applyTheDayDiscount(25)
+
+ Assertions.assertTrue(discountAmount == 3400)
+ }
+
+ @Test
+ fun `ํ์ผ ํ ์ธ ๊ธ์ก ํ
์คํธ`() {
+ val discountAmount = decemberEvent.applyWeekdayDiscount(listOf(OrderItems("์ด์ฝ์ผ์ดํฌ", 2), OrderItems("ํด์ฐ๋ฌผํ์คํ", 3)))
+
+ Assertions.assertTrue(discountAmount == 4046)
+ }
+
+ @Test
+ fun `์ฃผ๋ง ํ ์ธ ๊ธ์ก ํ
์คํธ`() {
+ val discountAmount = decemberEvent.applyWeekendDiscount(listOf(OrderItems("์ด์ฝ์ผ์ดํฌ", 2), OrderItems("ํด์ฐ๋ฌผํ์คํ", 3)))
+
+ Assertions.assertTrue(discountAmount == 6069)
+ }
+
+ @Test
+ fun `ํน๋ณ ํ ์ธ ๊ธ์ก ํ
์คํธ`() {
+ val discountAmount = decemberEvent.applySpecialDiscount()
+
+ Assertions.assertTrue(discountAmount == 1000)
+ }
+
+ @Test
+ fun `์ดํ์ธ ์ฆ์ ํ
์คํธ`() {
+ Assertions.assertTrue(decemberEvent.presentChampagne(130_000))
+ }
+
+ @Test
+ fun `๋ฐฐ์ง ๋ถ์ฌ ํ
์คํธ`() {
+ val noneBadge = decemberEvent.assignBadge(0)
+ val starBadge = decemberEvent.assignBadge(5000)
+ val treeBadge = decemberEvent.assignBadge(10000)
+ val santaBadge = decemberEvent.assignBadge(200000)
+
+ Assertions.assertTrue(noneBadge == "์์")
+ Assertions.assertTrue(starBadge == "๋ณ")
+ Assertions.assertTrue(treeBadge == "ํธ๋ฆฌ")
+ Assertions.assertTrue(santaBadge == "์ฐํ")
+ }
+}
\ No newline at end of file | Kotlin | ํ
์คํธ ์ฝ๋์ ๋ํด์๋ ์์ง ์ด๋ ค์์ ๋๋ผ๊ณ ์๊ธฐ ๋๋ฌธ์ ๋ง์ ํ์ต์ด ํ์ํ ๊ฒ ๊ฐ์์. ์์ธํ ์ค๋ช
๊ณผ ๋งํฌ๊น์ง..๋ฆฌ๋ทฐ ์ ๋ง ๊ฐ์ฌํฉ๋๋ค!! |
@@ -0,0 +1,79 @@
+package christmas.model
+
+import christmas.utils.Constant.BADGE_SANTA
+import christmas.utils.Constant.BADGE_STAR
+import christmas.utils.Constant.BADGE_TREE
+import christmas.utils.Constant.CHAMPAGNE_CONDITION_AMOUNT
+import christmas.utils.Constant.CHRISTMAS_DAY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.DAILY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.FIRST_DAY_DISCOUNT_AMOUNT
+import christmas.utils.Constant.EMPTY
+import christmas.utils.Constant.NONE
+import christmas.utils.Constant.ONE_DAY_DECREASE
+import christmas.utils.Constant.SANTA_MIN
+import christmas.utils.Constant.STAR_MAX
+import christmas.utils.Constant.STAR_MIN
+import christmas.utils.Constant.TREE_MAX
+import christmas.utils.Constant.TREE_MIN
+import christmas.utils.Constant.WEEK_DISCOUNT_AMOUNT
+
+class DecemberEvent {
+ fun applyTheDayDiscount(date: Int): Int {
+ val dailyDiscount = (date - ONE_DAY_DECREASE) * DAILY_DISCOUNT_AMOUNT
+
+ return FIRST_DAY_DISCOUNT_AMOUNT + dailyDiscount
+ }
+
+ fun applyWeekdayDiscount(orderMenu: List<OrderItems>): Int {
+ var dessertMenuCount = EMPTY
+
+ for (item in orderMenu) {
+ val increaseCount = increaseDessertMenuCount(item.getMenuName(), item.getQuantity())
+ dessertMenuCount += increaseCount
+ }
+
+ return dessertMenuCount * WEEK_DISCOUNT_AMOUNT
+ }
+
+ private fun increaseDessertMenuCount(menuName: String, quantity: Int): Int {
+ if (menuName == StoreMenu.CHOCO_CAKE.menuName || menuName == StoreMenu.ICE_CREAM.menuName)
+ return quantity
+
+ return EMPTY
+ }
+
+
+ fun applyWeekendDiscount(orderMenu: List<OrderItems>): Int {
+ var mainMenuCount = EMPTY
+
+ for (item in orderMenu) {
+ val increaseCount = increaseMainMenuCount(item.getMenuName(), item.getQuantity())
+ mainMenuCount += increaseCount
+ }
+
+ return mainMenuCount * WEEK_DISCOUNT_AMOUNT
+ }
+
+ private fun increaseMainMenuCount(menuName: String, quantity: Int): Int {
+ if (menuName == StoreMenu.T_BONE_STEAK.menuName || menuName == StoreMenu.BBQ_RIBS.menuName ||
+ menuName == StoreMenu.SEAFOOD_PASTA.menuName || menuName == StoreMenu.CHRISTMAS_PASTA.menuName
+ )
+ return quantity
+
+ return EMPTY
+ }
+
+ fun applySpecialDiscount(): Int = CHRISTMAS_DAY_DISCOUNT_AMOUNT
+
+ fun presentChampagne(totalOrderAmount: Int): Boolean = totalOrderAmount >= CHAMPAGNE_CONDITION_AMOUNT
+
+ fun assignBadge(benefitAmount: Int): String {
+ when {
+ benefitAmount in STAR_MIN..STAR_MAX -> return BADGE_STAR
+ benefitAmount in TREE_MIN..TREE_MAX -> return BADGE_TREE
+ benefitAmount >= SANTA_MIN -> return BADGE_SANTA
+ }
+
+ return NONE
+ }
+}
\ No newline at end of file | Kotlin | ํ ์ ๋๋ชจ๋ฅด๊ฒ when๋ฌธ ์์ ๋ค์ด์๋ else๋ if-else๋ ๋ค๋ฅด๋ค๊ณ ์๊ฐ์ ํ๊ณ ์์์ต๋๋ค..! ์ ๊ฐ ๋์น ๋ถ๋ถ์ ์ง์ด์ฃผ์
์ ๊ฐ์ฌํ๋ค์! |
@@ -0,0 +1,39 @@
+import { getProductListProps } from './product';
+
+interface Props extends getProductListProps {
+ baseUrl: string;
+}
+
+const buildGetProductListURL = ({
+ baseUrl,
+ category,
+ page,
+ size,
+ order,
+}: Props) => {
+ const params = [];
+
+ if (category) {
+ params.push(`category=${encodeURIComponent(category)}`);
+ }
+ if (page !== undefined) {
+ params.push(`page=${page}`);
+ }
+ if (size !== undefined) {
+ params.push(`size=${size}`);
+ }
+
+ if (order === 'desc') {
+ params.push(`sort=price%2C${order}&sort=name`);
+ } else {
+ params.push('sort=price&sort=name');
+ }
+
+ if (params.length > 0) {
+ baseUrl += `?${params.join('&')}`;
+ }
+
+ return baseUrl;
+};
+
+export default buildGetProductListURL; | TypeScript | api ๊ด๋ฆฌํ๊ฑฐ ๋ฉ์์ด์... ๐
step2 ๋ ์ ๋ ์ด๋ ๊ฒํด๋ณด๊ณ ์ถ๋ค์!! |
@@ -0,0 +1,47 @@
+import React from 'react';
+import styled from '@emotion/styled';
+import { theme } from '@/style/theme.style';
+
+type ButtonThemeType = 'dark' | 'light' | 'disabled';
+
+const BUTTON_THEME = {
+ dark: {
+ backgroundColor: theme.color.black,
+ color: theme.color.white,
+ },
+ light: {
+ backgroundColor: theme.color.lightGray,
+ color: theme.color.black,
+ },
+ disabled: {
+ backgroundColor: theme.color.gray,
+ color: theme.color.white,
+ },
+};
+
+interface Props extends React.ButtonHTMLAttributes<HTMLButtonElement> {
+ children?: React.ReactNode;
+ $theme?: ButtonThemeType;
+ $width?: string;
+ $height?: string;
+ $borderRadius?: string;
+}
+
+const BaseButton = ({ children, ...rest }: Props) => {
+ return <StyledButton {...rest}>{children}</StyledButton>;
+};
+
+export default BaseButton;
+
+const StyledButton = styled.button<Props>`
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ background-color: ${({ $theme }) =>
+ $theme ? BUTTON_THEME[$theme].backgroundColor : 'transparent'};
+ color: ${({ $theme }) => ($theme ? BUTTON_THEME[$theme].color : 'inherit')};
+ width: ${({ $width }) => ($width ? $width : 'fit-content')};
+ height: ${({ $height }) => ($height ? $height : 'fit-content')};
+ border-radius: ${({ $borderRadius }) =>
+ $borderRadius ? $borderRadius : '4px'};
+`; | Unknown | styled ์ด๋ ๊ฒ ํ ํ์ผ์ ์ ๋๊ฒ๋ ๊ฐ๋
์ฑ ์ข๋ค์
์ ๋ emotion ์ผ๋๋ฐ ui ์์
ํ๋ฉด์ ๊ณ์ ์๋ฆฌ๊ฐ๋ฆฌํ๋ ๊ฒฝํ์ด์์ด์.. |
@@ -0,0 +1,49 @@
+package com.codesquad.rocket.config;
+
+import java.io.IOException;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.http.HttpHeaders;
+import org.springframework.stereotype.Component;
+
+@Component
+public class SimpleCorsFilter implements Filter {
+
+ private final Logger logger = LoggerFactory.getLogger(SimpleCorsFilter.class);
+
+ public SimpleCorsFilter() {
+ logger.info("SimpleCORSFilter init");
+ }
+
+ @Override
+ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws
+ IOException, ServletException {
+
+ HttpServletRequest request = (HttpServletRequest) req;
+ HttpServletResponse response = (HttpServletResponse) res;
+ response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, request.getHeader("Origin"));
+ response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
+ response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "POST, GET, OPTIONS, DELETE, PUT, PATCH");
+ response.setHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3600");
+ response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Content-Type, Accept, X-Requested-With, remember-me, Authorization");
+ chain.doFilter(req, res);
+ }
+
+ @Override
+ public void init(FilterConfig filterConfig) {
+ }
+
+ @Override
+ public void destroy() {
+ }
+} | Java | HttpHeaders์ static finalํ ํํ๋ก ํค๋์ ์ง์ ํ๋ ํ
์คํธ๊ฐ ์ด๋ฏธ ์กด์ฌํ๋ค. ์ด๋ฅผ ์ฌ์ฉํ์ฌ ๋ฆฌํฉํ ๋งํ๋ค. |
@@ -0,0 +1,35 @@
+package christmas.domain.discount.policy;
+
+import christmas.domain.common.Date;
+import christmas.domain.common.Money;
+import christmas.domain.discount.DateDiscountPolicy;
+import christmas.domain.discount.DiscountResult;
+
+public class ChristmasDDayDiscountPolicy extends DateDiscountPolicy {
+
+ private static final Date DISCOUNTABLE_STANDARD_DATE = Date.from(25);
+ private static final Money BASE_DISCOUNT_AMOUNT = Money.from(-1_000);
+ private static final Money ADD_AMOUNT = Money.from(-100);
+ private static final String POLICY_NAME = "ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ";
+
+ @Override
+ protected boolean isSatisfied(Date date) {
+ return !date.isLaterThan(DISCOUNTABLE_STANDARD_DATE);
+ }
+
+ @Override
+ protected DiscountResult bulidDiscountResult(Date date) {
+ Money discountAmount = calculateDiscountAmount(date);
+
+ return new DiscountResult(POLICY_NAME, discountAmount);
+ }
+
+ private Money calculateDiscountAmount(Date date) {
+ Money discountAmount = BASE_DISCOUNT_AMOUNT;
+ for (int day = 1; day < date.getDayOfMonth(); day++) {
+ discountAmount = discountAmount.add(ADD_AMOUNT);
+ }
+
+ return discountAmount;
+ }
+} | Java | ์ด๋ ๊ฒ ํ๋ฉด, ๋งค ๋ฐ๋ณต๋ง๋ค getDayOfMonth ๋ฉ์๋๋ฅผ ํธ์ถํ๊ธฐ ๋๋ฌธ์ ์ฑ๋ฅ๋ฉด์์ ์ข์ง ์์๊ฑฐ ๊ฐ์์! ์ง๊ธ์ getDayOfMonth์ ๋ณต์กํ ๋ก์ง์ด ์์ด ํฌ๊ฒ ์ฐจ์ด๋ ์์๊ฑฐ ๊ฐ์ง๋ง, ์์ ๊ฐ์ ์ฝ๋๋ ์ฑ๋ฅ ์ด์๊ฐ ๋ฐ์ํ ์ ์๋ค๊ณ ์๊ฐํฉ๋๋ค. ํด๋น ๋ฉ์๋์ ๊ฐ์ ๋ณ์๋ก ํ ๋นํด ์ฌ์ฉํ๋ ๊ฒ์ ์ด๋ค๊ฐ์? ๐ |
@@ -0,0 +1,55 @@
+package christmas.domain.menu;
+
+import christmas.domain.common.Date;
+import christmas.domain.common.Money;
+import christmas.domain.discount.DateDiscountPolicy;
+import christmas.domain.discount.DiscountResult;
+import java.util.Objects;
+
+public abstract class AbstractMenu implements Menu {
+
+ protected final MenuName name;
+ protected final Money price;
+ protected final DateDiscountPolicy policy;
+
+ protected AbstractMenu(MenuName name, Money price, DateDiscountPolicy policy) {
+ this.name = name;
+ this.price = price;
+ this.policy = policy;
+ }
+
+ @Override
+ public Money calculatePriceWith(int quantity) {
+ return price.multiply(quantity);
+ }
+
+ @Override
+ public DiscountResult calculateDiscountBenefitWith(Date date, int quantity) {
+ DiscountResult menuDiscountResult = policy.discount(date);
+
+ return new DiscountResult(menuDiscountResult.policyName(), menuDiscountResult.amount().multiply(quantity));
+ }
+
+ @Override
+ public boolean isDiscountable(Date date) {
+ return policy.isDiscountable(date);
+ }
+
+ @Override
+ public String getName() {
+ return name.getName();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ AbstractMenu that = (AbstractMenu) o;
+ return Objects.equals(name, that.name) && Objects.equals(price, that.price);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(name, price);
+ }
+} | Java | ์ค์ ์ถ์ ํด๋์ค๋ก ์ ์ธํ ์ด์ ๊ฐ ๊ถ๊ธํด์. ์ ๊ฐ ๋ดค์ ๋ ์ถ์ ๋ฉ์๋๊ฐ ์๋๊ฑฐ ๊ฐ์๋ฐ ๋ง์๊น์? ์ถ์ ๋ฉ์๋๊ฐ ์๋๋ฐ ์ถ์ ํด๋์ค๋ก ์ ์ธํ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค! |
@@ -0,0 +1,35 @@
+package christmas.domain.discount.policy;
+
+import christmas.domain.common.Date;
+import christmas.domain.common.Money;
+import christmas.domain.discount.DateDiscountPolicy;
+import christmas.domain.discount.DiscountResult;
+
+public class ChristmasDDayDiscountPolicy extends DateDiscountPolicy {
+
+ private static final Date DISCOUNTABLE_STANDARD_DATE = Date.from(25);
+ private static final Money BASE_DISCOUNT_AMOUNT = Money.from(-1_000);
+ private static final Money ADD_AMOUNT = Money.from(-100);
+ private static final String POLICY_NAME = "ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ";
+
+ @Override
+ protected boolean isSatisfied(Date date) {
+ return !date.isLaterThan(DISCOUNTABLE_STANDARD_DATE);
+ }
+
+ @Override
+ protected DiscountResult bulidDiscountResult(Date date) {
+ Money discountAmount = calculateDiscountAmount(date);
+
+ return new DiscountResult(POLICY_NAME, discountAmount);
+ }
+
+ private Money calculateDiscountAmount(Date date) {
+ Money discountAmount = BASE_DISCOUNT_AMOUNT;
+ for (int day = 1; day < date.getDayOfMonth(); day++) {
+ discountAmount = discountAmount.add(ADD_AMOUNT);
+ }
+
+ return discountAmount;
+ }
+} | Java | ๋ถ๊ณผ ๋ช๋ฌ์ ์ ์ฑ
์์ ๋ดค๋ ๋ด์ฉ์ด๋ค์.. ์ด์ ์ ๋ ๊น๋จน์๋ฆฌ ์์ ๊ฒ ๊ฐ๋ค์! ๊ฐ์ฌํฉ๋๋ค ๐๐ปโโ๏ธ |
@@ -0,0 +1,55 @@
+package christmas.domain.menu;
+
+import christmas.domain.common.Date;
+import christmas.domain.common.Money;
+import christmas.domain.discount.DateDiscountPolicy;
+import christmas.domain.discount.DiscountResult;
+import java.util.Objects;
+
+public abstract class AbstractMenu implements Menu {
+
+ protected final MenuName name;
+ protected final Money price;
+ protected final DateDiscountPolicy policy;
+
+ protected AbstractMenu(MenuName name, Money price, DateDiscountPolicy policy) {
+ this.name = name;
+ this.price = price;
+ this.policy = policy;
+ }
+
+ @Override
+ public Money calculatePriceWith(int quantity) {
+ return price.multiply(quantity);
+ }
+
+ @Override
+ public DiscountResult calculateDiscountBenefitWith(Date date, int quantity) {
+ DiscountResult menuDiscountResult = policy.discount(date);
+
+ return new DiscountResult(menuDiscountResult.policyName(), menuDiscountResult.amount().multiply(quantity));
+ }
+
+ @Override
+ public boolean isDiscountable(Date date) {
+ return policy.isDiscountable(date);
+ }
+
+ @Override
+ public String getName() {
+ return name.getName();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ AbstractMenu that = (AbstractMenu) o;
+ return Objects.equals(name, that.name) && Objects.equals(price, that.price);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(name, price);
+ }
+} | Java | ์ง์ ์์ฑํ๋ ๊ฒ์ ๋ง๊ณ , ๊ณตํต ๋ก์ง์ ์ฌ์ฌ์ฉํ๊ธฐ ์ํด์ abstract๋ก ๋ง๋ค์์ด์! ํ์ง๋ง, ํ๋๋์ฒ๋ผ ํ์
๊ธฐ๋ฐ์ผ๋ก ๋ฉ๋ด๋ฅผ ๋ถ๋ฅํ๋ฉด ์ด๋ฐ ์ฝ๋๋ ๋ถํ์ํ ๊ฒ ๊ฐ๋ค์! |
@@ -0,0 +1,77 @@
+package christmas.domain.common;
+
+import static christmas.global.util.ObjectUtil.requireNonNull;
+
+import christmas.global.util.DateUtil;
+import java.util.Objects;
+
+public class Date {
+
+ public static final int BASE_MONTH = 12;
+ private static final int BASE_YEAR = 2023;
+ private static final int DAY_OF_MONTH_MIN_RANGE = 1;
+ private static final int DAY_OF_MONTH_MAX_RANGE = 31;
+ private static final String INVALID_DAY_OF_MONTH_RANGE_MESSAGE =
+ "๋ ์ง๋ " + DAY_OF_MONTH_MIN_RANGE + "๊ณผ " + DAY_OF_MONTH_MAX_RANGE + " ์ฌ์ด์ ์๋ฅผ ์
๋ ฅํด์ฃผ์ธ์.";
+ private static final String UNKNOWN_DATE_MESSAGE = "์ ์ ์๋ ๋ ์ง์
๋๋ค.";
+
+ private final int dayOfMonth;
+
+ private Date(int dayOfMonth) {
+ this.dayOfMonth = dayOfMonth;
+ }
+
+ public static Date from(int dayOfMonth) {
+ checkDayOfMonthRange(dayOfMonth);
+
+ return new Date(dayOfMonth);
+ }
+
+ private static void checkDayOfMonthRange(int dayOfMonth) {
+ checkDayOfMonthMinRange(dayOfMonth);
+ checkDayOfMonthMaxRange(dayOfMonth);
+ }
+
+ private static void checkDayOfMonthMinRange(int dayOfMonth) {
+ if (dayOfMonth < DAY_OF_MONTH_MIN_RANGE) {
+ throw new IllegalArgumentException(INVALID_DAY_OF_MONTH_RANGE_MESSAGE);
+ }
+ }
+
+ private static void checkDayOfMonthMaxRange(int dayOfMonth) {
+ if (dayOfMonth > DAY_OF_MONTH_MAX_RANGE) {
+ throw new IllegalArgumentException(INVALID_DAY_OF_MONTH_RANGE_MESSAGE);
+ }
+ }
+
+ public boolean isLaterThan(Date target) {
+ requireNonNull(target, UNKNOWN_DATE_MESSAGE);
+
+ return this.dayOfMonth > target.dayOfMonth;
+ }
+
+ public boolean isWeekDay() {
+ return DateUtil.isWeekday(BASE_YEAR, BASE_MONTH, dayOfMonth);
+ }
+
+ public boolean isWeekend() {
+ return DateUtil.isWeekend(BASE_YEAR, BASE_MONTH, dayOfMonth);
+ }
+
+ public int getDayOfMonth() {
+ return dayOfMonth;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Date date = (Date) o;
+ return dayOfMonth == date.dayOfMonth;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(dayOfMonth);
+ }
+} | Java | > ๋ฐฉ๋ฌธํ ๋ ์ง๋ 1 ์ด์ 31 ์ดํ์ ์ซ์๋ก๋ง ์
๋ ฅ๋ฐ์ ์ฃผ์ธ์.
> 1 ์ด์ 31 ์ดํ์ ์ซ์๊ฐ ์๋ ๊ฒฝ์ฐ, "[ERROR] ์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."๋ผ๋ ์๋ฌ ๋ฉ์์ง๋ฅผ ๋ณด์ฌ ์ฃผ์ธ์.
์๊ตฌ์ฌํญ์์ ๋ช
์ํ ์์ธ ๋ฉ์์ง ๋ง๊ณ ์ด๋ฌํ ์์ธ ๋ฉ์์ง๋ฅผ ์ ํํ ์ด์ ๋ ๊ตฌ์ฒด์ฑ์ ๋์ด๊ธฐ ์ํจ์ด์๋์ ? ๐ |
@@ -0,0 +1,63 @@
+package christmas.domain.common;
+
+import static christmas.global.util.ObjectUtil.requireNonNull;
+
+import java.util.Objects;
+
+public class Money {
+
+ private static final int ZERO_MONEY_AMOUNT = 0;
+ private static final String UNKNOWN_MONEY_MESSAGE = "์ ์ ์๋ ๋๊ณผ ํด๋น ์ฐ์ฐ์ ์ํํ ์ ์์ต๋๋ค.";
+ public static final String CURRENCY = "์";
+
+ private final long amount;
+
+ private Money(long amount) {
+ this.amount = amount;
+ }
+
+ public static Money from(long amount) {
+ return new Money(amount);
+ }
+
+ public static Money zero() {
+ return new Money(ZERO_MONEY_AMOUNT);
+ }
+
+ public Money add(Money target) {
+ requireNonNull(target, UNKNOWN_MONEY_MESSAGE);
+
+ return new Money(this.amount + target.amount);
+ }
+
+ public Money subtract(Money target) {
+ requireNonNull(target, UNKNOWN_MONEY_MESSAGE);
+
+ return new Money(this.amount - target.amount);
+ }
+
+ public Money multiply(int multiplier) {
+ return new Money(this.amount * multiplier);
+ }
+
+ public boolean isGreaterThanEqual(int amount) {
+ return this.amount >= amount;
+ }
+
+ public long getAmount() {
+ return amount;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Money money = (Money) o;
+ return amount == money.amount;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(amount);
+ }
+} | Java | ๋ถ๋ณ ๊ฐ์ฒด๋ก ํ์ฉํ ์ ์ด ์ข๋ค์ ~ ๐ |
@@ -0,0 +1,30 @@
+package christmas.domain.discount;
+
+import static christmas.global.util.ObjectUtil.requireNonNull;
+
+import christmas.domain.common.Date;
+
+public abstract class DateDiscountPolicy {
+
+ private static final String UNKNOWN_DATE_MESSAGE = "์ ์ ์๋ ๋ ์ง์
๋๋ค.";
+ private static final String CANT_APPLY_DISCOUNT_MESSAGE = "ํ ์ธ์ ์ ์ฉํ ์ ์์ต๋๋ค.";
+
+ public DiscountResult discount(Date date) {
+ requireNonNull(date, UNKNOWN_DATE_MESSAGE);
+ if (!isDiscountable(date)) {
+ throw new IllegalStateException(CANT_APPLY_DISCOUNT_MESSAGE);
+ }
+
+ return bulidDiscountResult(date);
+ }
+
+ public boolean isDiscountable(Date date) {
+ requireNonNull(date, UNKNOWN_DATE_MESSAGE);
+
+ return isSatisfied(date);
+ }
+
+ protected abstract boolean isSatisfied(Date date);
+
+ protected abstract DiscountResult bulidDiscountResult(Date date);
+} | Java | ํ์ ์์ ๊ตฌํ์ฒด๊ฐ ์์ ๋ถ๋ชจ ๊ฐ์ฒด์ ๋ก์ง์ ์ํฅ์ ์ฃผ๊ธฐ ์ํด์ protected abstract๋ก ์ ์ธํ ๊ฒ์ด ์ธ์์ ์ด๋ค์~ ๐ |
@@ -0,0 +1,18 @@
+package christmas.domain.discount.policy;
+
+import christmas.domain.common.Date;
+import christmas.domain.discount.DateDiscountPolicy;
+import christmas.domain.discount.DiscountResult;
+
+public class NoneDiscountPolicy extends DateDiscountPolicy {
+
+ @Override
+ protected boolean isSatisfied(Date date) {
+ return false;
+ }
+
+ @Override
+ protected DiscountResult bulidDiscountResult(Date date) {
+ return null;
+ }
+} | Java | ํด๋น Policy๋ ์ด๋ค ์ด์ ๋๋ฌธ์ ๊ตฌ์ฑํ์
จ๋์ ~ ? ๐ |
@@ -0,0 +1,35 @@
+package christmas.domain.discount.policy;
+
+import christmas.domain.common.Date;
+import christmas.domain.common.Money;
+import christmas.domain.discount.DateDiscountPolicy;
+import christmas.domain.discount.DiscountResult;
+
+public class ChristmasDDayDiscountPolicy extends DateDiscountPolicy {
+
+ private static final Date DISCOUNTABLE_STANDARD_DATE = Date.from(25);
+ private static final Money BASE_DISCOUNT_AMOUNT = Money.from(-1_000);
+ private static final Money ADD_AMOUNT = Money.from(-100);
+ private static final String POLICY_NAME = "ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ";
+
+ @Override
+ protected boolean isSatisfied(Date date) {
+ return !date.isLaterThan(DISCOUNTABLE_STANDARD_DATE);
+ }
+
+ @Override
+ protected DiscountResult bulidDiscountResult(Date date) {
+ Money discountAmount = calculateDiscountAmount(date);
+
+ return new DiscountResult(POLICY_NAME, discountAmount);
+ }
+
+ private Money calculateDiscountAmount(Date date) {
+ Money discountAmount = BASE_DISCOUNT_AMOUNT;
+ for (int day = 1; day < date.getDayOfMonth(); day++) {
+ discountAmount = discountAmount.add(ADD_AMOUNT);
+ }
+
+ return discountAmount;
+ }
+} | Java | ๊ฐ์ธ์ ์ผ๋ก ์ ํ ์ธ๋ ๊ธ์ก์ ์์ ๊ฐ์ผ๋ก ์ ์งํ๊ณ , View๋ก ๋ณด์ฌ์ฃผ๋ ์์ ์ "-" ๋ง์ด๋์ค ๋ถํธ๋ฅผ ๋ถ์ฌ์ฃผ๋๋ก ํ์ฉํจ์ผ๋ก์จ
์ด ๊ธ์ก์ด ์ฃผ๋ฌธ ๊ธ์ก์์ ์ผ๋ง๋ ๋นผ์ผ ํ ๊ธ์ก์ธ์ง๋ฅผ ์ง๊ด์ ์ผ๋ก ์ดํดํ ์ ์๋๋ก ์๋ํ๋๋ฐ
ํ๋๋์ ์ด๋ค ์ด์ ๋๋ฌธ์ ์ฒ์๋ถํฐ ํ ์ธ๋ ๊ธ์ก์ ์์ ๊ฐ์ผ๋ฃ ์ ์งํ๊ณ ์ ํ์
จ๋์~? ๐ |
@@ -0,0 +1,35 @@
+package christmas.domain.discount.policy;
+
+import christmas.domain.common.Date;
+import christmas.domain.common.Money;
+import christmas.domain.discount.DateDiscountPolicy;
+import christmas.domain.discount.DiscountResult;
+import java.util.List;
+
+public class SpecialDiscountPolicy extends DateDiscountPolicy {
+
+ private static final List<Date> specialDays;
+ private static final Money DISCOUNT_AMOUNT = Money.from(-1_000);
+ private static final String POLICY_NAME = "ํน๋ณ ํ ์ธ";
+
+ static {
+ specialDays = List.of(
+ Date.from(3),
+ Date.from(10),
+ Date.from(17),
+ Date.from(24),
+ Date.from(25),
+ Date.from(31)
+ );
+ }
+
+ @Override
+ protected boolean isSatisfied(Date date) {
+ return specialDays.contains(date);
+ }
+
+ @Override
+ protected DiscountResult bulidDiscountResult(Date date) {
+ return new DiscountResult(POLICY_NAME, DISCOUNT_AMOUNT);
+ }
+} | Java | ํน๋ณํ ๋ ์ง๋ฅผ ๊ด๋ฆฌํ๊ธฐ ์ํด์ List๋ฅผ ํ์ฉํ์
จ๋๋ฐ, Set์ ์ด๋จ๊น์~ ? ๐ |
@@ -0,0 +1,46 @@
+package christmas.domain.menu;
+
+import static christmas.global.util.ObjectUtil.requireIncludeNonNull;
+import static christmas.global.util.ObjectUtil.requireNonNull;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Objects;
+
+public class Menus {
+
+ private static final String UNKNOWN_MENUS_MESSAGE = "์ ์ ์๋ ๋ฉ๋ด ๋ชฉ๋ก์
๋๋ค.";
+ private static final String UNKNOWN_MENU_MESSAGE = "์ ์ ์๋ ๋ฉ๋ด๊ฐ ํฌํจ๋์ด ์์ต๋๋ค.";
+
+ private final List<Menu> menus;
+
+ private Menus(List<Menu> menus) {
+ this.menus = menus;
+ }
+
+ public static Menus from(List<Menu> menus) {
+ requireNonNull(menus, UNKNOWN_MENUS_MESSAGE);
+ requireIncludeNonNull(menus, UNKNOWN_MENU_MESSAGE);
+
+ return new Menus(menus);
+ }
+
+ public boolean containsAll(Menus other) {
+ requireNonNull(other, UNKNOWN_MENUS_MESSAGE);
+
+ return new HashSet<>(menus).containsAll(other.menus);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Menus menus1 = (Menus) o;
+ return Objects.equals(menus, menus1.menus);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(menus);
+ }
+} | Java | List์ Set์ผ๋ก ๋ณ๊ฒฝํด์ ํ์ธํ๋ ๋ถ๋ถ์ด ์ข๋ค์ ~ ๐ |
@@ -0,0 +1,77 @@
+package christmas.domain.common;
+
+import static christmas.global.util.ObjectUtil.requireNonNull;
+
+import christmas.global.util.DateUtil;
+import java.util.Objects;
+
+public class Date {
+
+ public static final int BASE_MONTH = 12;
+ private static final int BASE_YEAR = 2023;
+ private static final int DAY_OF_MONTH_MIN_RANGE = 1;
+ private static final int DAY_OF_MONTH_MAX_RANGE = 31;
+ private static final String INVALID_DAY_OF_MONTH_RANGE_MESSAGE =
+ "๋ ์ง๋ " + DAY_OF_MONTH_MIN_RANGE + "๊ณผ " + DAY_OF_MONTH_MAX_RANGE + " ์ฌ์ด์ ์๋ฅผ ์
๋ ฅํด์ฃผ์ธ์.";
+ private static final String UNKNOWN_DATE_MESSAGE = "์ ์ ์๋ ๋ ์ง์
๋๋ค.";
+
+ private final int dayOfMonth;
+
+ private Date(int dayOfMonth) {
+ this.dayOfMonth = dayOfMonth;
+ }
+
+ public static Date from(int dayOfMonth) {
+ checkDayOfMonthRange(dayOfMonth);
+
+ return new Date(dayOfMonth);
+ }
+
+ private static void checkDayOfMonthRange(int dayOfMonth) {
+ checkDayOfMonthMinRange(dayOfMonth);
+ checkDayOfMonthMaxRange(dayOfMonth);
+ }
+
+ private static void checkDayOfMonthMinRange(int dayOfMonth) {
+ if (dayOfMonth < DAY_OF_MONTH_MIN_RANGE) {
+ throw new IllegalArgumentException(INVALID_DAY_OF_MONTH_RANGE_MESSAGE);
+ }
+ }
+
+ private static void checkDayOfMonthMaxRange(int dayOfMonth) {
+ if (dayOfMonth > DAY_OF_MONTH_MAX_RANGE) {
+ throw new IllegalArgumentException(INVALID_DAY_OF_MONTH_RANGE_MESSAGE);
+ }
+ }
+
+ public boolean isLaterThan(Date target) {
+ requireNonNull(target, UNKNOWN_DATE_MESSAGE);
+
+ return this.dayOfMonth > target.dayOfMonth;
+ }
+
+ public boolean isWeekDay() {
+ return DateUtil.isWeekday(BASE_YEAR, BASE_MONTH, dayOfMonth);
+ }
+
+ public boolean isWeekend() {
+ return DateUtil.isWeekend(BASE_YEAR, BASE_MONTH, dayOfMonth);
+ }
+
+ public int getDayOfMonth() {
+ return dayOfMonth;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Date date = (Date) o;
+ return dayOfMonth == date.dayOfMonth;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(dayOfMonth);
+ }
+} | Java | ๋ต ๋ง์ต๋๋ค. ์๊ตฌ์ฌํญ์ ๋์ค๋ ์์ธ ๋ฉ์์ง๋ ๋๋ฌด ์ผ๋ฐ์ ์ฌ์์. ๊ฐ๋ฐํ๋ฉด์ ๋ก๊ทธ๋ฅผ ์ฐ์ด ๋ณผ ์ผ์ด ์์๋๋ฐ, ๋ถํธํ๋๋ผ๊ตฌ์. ๋ฐ๋ผ์, ์์ ๊ฐ์ด ๊ตฌ์ฒด์ ์ผ๋ก ๋ด๋ณด๋ด๊ณ , ๋ค์ ์ปจํธ๋กค๋ฌ์์ ๋ฉ์์ง๋ฅผ ๋ฐ๊พธ๋ ์์
์ ํด์คฌ์ต๋๋ค! |
@@ -0,0 +1,18 @@
+package christmas.domain.discount.policy;
+
+import christmas.domain.common.Date;
+import christmas.domain.discount.DateDiscountPolicy;
+import christmas.domain.discount.DiscountResult;
+
+public class NoneDiscountPolicy extends DateDiscountPolicy {
+
+ @Override
+ protected boolean isSatisfied(Date date) {
+ return false;
+ }
+
+ @Override
+ protected DiscountResult bulidDiscountResult(Date date) {
+ return null;
+ }
+} | Java | ```java
@Override
public DiscountResult calculateDiscountBenefitWith(Date date, int quantity) {
DiscountResult menuDiscountResult = policy.discount(date);
return new DiscountResult(menuDiscountResult.policyName(), menuDiscountResult.amount().multiply(quantity));
}
```
DateDiscountPolicy๋ฅผ ์ฌ์ฉํ๋ ํด๋ผ์ด์ธํธ ์ฝ๋๋ ์์ ๊ฐ์ ํํ๋ก discount(๋ด๋ถ์์ buildDiscountResult, isSatisfied ํธ์ถ)๋ฅผ ํธ์ถํ๋๋ฐ์. ๋ฉ๋ด๊ฐ ์ ์ฑ
์ด ์๋ ๊ฒ์ ์ด๊ณณ์์ ํ๋จํ๊ธฐ ๋ณด๋ค๋, NoneDiscountPolicy๋ฅผ ๋ง๋ค์ด์ ํด๋ผ์ด์ธํธ ์ฝ๋๋ฅผ ์ฌ์ฌ์ฉํ๊ธฐ ์ํจ์
๋๋ค.! |
@@ -0,0 +1,35 @@
+package christmas.domain.discount.policy;
+
+import christmas.domain.common.Date;
+import christmas.domain.common.Money;
+import christmas.domain.discount.DateDiscountPolicy;
+import christmas.domain.discount.DiscountResult;
+
+public class ChristmasDDayDiscountPolicy extends DateDiscountPolicy {
+
+ private static final Date DISCOUNTABLE_STANDARD_DATE = Date.from(25);
+ private static final Money BASE_DISCOUNT_AMOUNT = Money.from(-1_000);
+ private static final Money ADD_AMOUNT = Money.from(-100);
+ private static final String POLICY_NAME = "ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ";
+
+ @Override
+ protected boolean isSatisfied(Date date) {
+ return !date.isLaterThan(DISCOUNTABLE_STANDARD_DATE);
+ }
+
+ @Override
+ protected DiscountResult bulidDiscountResult(Date date) {
+ Money discountAmount = calculateDiscountAmount(date);
+
+ return new DiscountResult(POLICY_NAME, discountAmount);
+ }
+
+ private Money calculateDiscountAmount(Date date) {
+ Money discountAmount = BASE_DISCOUNT_AMOUNT;
+ for (int day = 1; day < date.getDayOfMonth(); day++) {
+ discountAmount = discountAmount.add(ADD_AMOUNT);
+ }
+
+ return discountAmount;
+ }
+} | Java | View์์ ๋ง์ด๋์ค ๋ถํธ๋ฅผ ์ถ๊ฐํด์ฃผ๋ ๊ฒ์ด ๋ฒ๊ฑฐ๋ก์์ ๊ทธ๋ฐ์์ผ๋ก ๊ตฌํํ๋ ๊ฒ ๊ฐ์ต๋๋ค. ํ์คํ ์์๋ก ํ๋ ๊ฒ์ด, ๋ง์ ์ฃผ์ ๊ฒ์ฒ๋ผ ๋์ฑ ์ง๊ด์ ์ธ ๊ฒ ๊ฐ์์!
++ Money์ substract ์ฐ์ฐ์ ๋ง๋ ์ด์ ๋ ์ฒ์์๋ ํ ์ธ ๊ฐ์ ์์๋ก ์ ์งํ๋ ค๊ณ ํ๋ ๊ฒ ๊ฐ์๋ฐ์. ์ง๊ธ๋ณด๋, money.substract๋ฅผ ํ
์คํธ ์ฝ๋์์๋ง ์ฌ์ฉํ๋๊ตฐ์... ํผ๋๋ฐฑ ๊ฐ์ฌํฉ๋๋ค. |
@@ -0,0 +1,84 @@
+import { ๋น๋๊ธฐ_์์ฒญ } from 'constants/';
+
+const errorReturn = (error) => ({
+ status: ๋น๋๊ธฐ_์์ฒญ.FAIL,
+ content: `์๋ฒ์์ ํต์ ์ ์คํจํ์์ต๋๋ค. (${error.message})`,
+});
+
+const authorizedHeader = (header) => ({
+ ...header,
+ Authorization: `Bearer ${sessionStorage.getItem('accessToken')}`,
+});
+
+class RequestAsync {
+ constructor() {
+ this.HOST_NAME = process.env.REACT_APP_API_URL;
+ this.header = { 'Content-Type': 'application/json' };
+ }
+
+ async #getRefinedResponse(response) {
+ const responseString = await response.text();
+
+ return {
+ status: response.ok ? ๋น๋๊ธฐ_์์ฒญ.SUCCESS : ๋น๋๊ธฐ_์์ฒญ.FAILURE,
+ content: responseString ? JSON.parse(responseString) : {},
+ };
+ }
+
+ async get(path, authorize = false) {
+ try {
+ const response = await fetch(`${this.HOST_NAME}/${path}`, {
+ method: 'GET',
+ headers: authorize ? authorizedHeader(this.header) : this.header,
+ });
+
+ return this.#getRefinedResponse(response);
+ } catch (error) {
+ return errorReturn(error);
+ }
+ }
+
+ async post(path, bodyData, authorize = false) {
+ try {
+ const response = await fetch(`${this.HOST_NAME}/${path}`, {
+ method: 'POST',
+ headers: authorize ? authorizedHeader(this.header) : this.header,
+ body: JSON.stringify(bodyData),
+ });
+
+ return this.#getRefinedResponse(response);
+ } catch (error) {
+ return errorReturn(error);
+ }
+ }
+
+ async put(path, bodyData, authorize = false) {
+ try {
+ const response = await fetch(`${this.HOST_NAME}/${path}`, {
+ method: 'PUT',
+ headers: authorize ? authorizedHeader(this.header) : this.header,
+ body: JSON.stringify(bodyData),
+ });
+
+ return this.#getRefinedResponse(response);
+ } catch (error) {
+ return errorReturn(error);
+ }
+ }
+
+ async delete(path, authorize = false) {
+ try {
+ const response = await fetch(`${this.HOST_NAME}/${path}`, {
+ method: 'DELETE',
+ headers: authorize ? authorizedHeader(this.header) : this.header,
+ });
+
+ return this.#getRefinedResponse(response);
+ } catch (error) {
+ return errorReturn(error);
+ }
+ }
+}
+
+const requestAsync = new RequestAsync();
+export default requestAsync; | JavaScript | ์ค~ |
@@ -0,0 +1,67 @@
+package com.codesquad.airbnb.business;
+
+import com.codesquad.airbnb.exception.ErrorMessage;
+import com.codesquad.airbnb.exception.custom.EntityNotFoundException;
+import com.codesquad.airbnb.common.utils.DAOUtils;
+import com.codesquad.airbnb.dao.AccommodationMapper;
+import com.codesquad.airbnb.dao.BookingMapper;
+import com.codesquad.airbnb.dao.FeePolicyMapper;
+import com.codesquad.airbnb.domain.dto.AccommodationDTO;
+import com.codesquad.airbnb.domain.model.Accommodation;
+import com.codesquad.airbnb.domain.model.Booking;
+import com.codesquad.airbnb.domain.model.Filter;
+import com.codesquad.airbnb.domain.model.User;
+import org.springframework.stereotype.Service;
+
+import java.util.Map;
+
+@Service
+public class BookService {
+
+ private AccommodationMapper accommodationMapper;
+ private FeePolicyMapper feePolicyMapper;
+ private BookingMapper bookingMapper;
+
+ public BookService(AccommodationMapper accommodationMapper,
+ FeePolicyMapper feePolicyMapper,
+ BookingMapper bookingMapper) {
+ this.accommodationMapper = accommodationMapper;
+ this.feePolicyMapper = feePolicyMapper;
+ this.bookingMapper = bookingMapper;
+ }
+
+ public AccommodationDTO getAccommodation(Integer id, Filter filter) {
+ if(accommodationMapper.countById(id) == 0) {
+ throw new EntityNotFoundException(ErrorMessage.ENTITY_NOT_FOUND.getMessage());
+ }
+
+ Map<String, Object> parameters = DAOUtils.createParameters(filter, id);
+ Accommodation accommodation = accommodationMapper.findAccommodationChargeInfoById(parameters);
+
+ float accommodationTaxRate = feePolicyMapper.findAccommodationTax();
+
+ return new AccommodationDTO.Builder(accommodation.getId())
+ .pricePerNight(accommodation.getOriginalPricePerNight())
+ .pricePerNightDiscounted(accommodation.getDiscountedPricePerNight())
+ .priceDuringPeriod(accommodation.getPriceDuringPeriod(filter))
+ .cleaningFee(accommodation.getCleaningFee())
+ .serviceTax(accommodation.getServiceTax(filter))
+ .accommodationTax(accommodation.getAccommodationTax(filter, accommodationTaxRate))
+ .totalPrice(accommodation.getTotalPrice(filter, accommodationTaxRate))
+ .build();
+ }
+
+ public boolean booking(Integer id, Filter filter, User user) {
+ if(accommodationMapper.countById(id) == 0) {
+ throw new EntityNotFoundException(ErrorMessage.ENTITY_NOT_FOUND.getMessage());
+ }
+
+ Booking newBooking = new Booking(user, id, filter);
+
+ if (bookingMapper.countByAccommodationIdAndPeriod(newBooking) > 0) {
+ return false;
+ }
+ bookingMapper.insertBooking(newBooking);
+ return true;
+ }
+} | Java | ๋จ์ํ null-safety๋ฅผ ์ํด ์นด์ดํธ ๋ก์ง์ ํ ๋ฒ ๋ ๋ฃ์ ๊ฑฐ๋ผ๋ฉด,
null check๋ฅผ ํ๋ ๊ฒ์ด ์ฑ๋ฅ์์ ๋ ํฐ ์ด์ ์ด ์์ ๊ฒ ๊ฐ๋ค์. |
@@ -0,0 +1,67 @@
+package com.codesquad.airbnb.business;
+
+import com.codesquad.airbnb.exception.ErrorMessage;
+import com.codesquad.airbnb.exception.custom.EntityNotFoundException;
+import com.codesquad.airbnb.common.utils.DAOUtils;
+import com.codesquad.airbnb.dao.AccommodationMapper;
+import com.codesquad.airbnb.dao.BookingMapper;
+import com.codesquad.airbnb.dao.FeePolicyMapper;
+import com.codesquad.airbnb.domain.dto.AccommodationDTO;
+import com.codesquad.airbnb.domain.model.Accommodation;
+import com.codesquad.airbnb.domain.model.Booking;
+import com.codesquad.airbnb.domain.model.Filter;
+import com.codesquad.airbnb.domain.model.User;
+import org.springframework.stereotype.Service;
+
+import java.util.Map;
+
+@Service
+public class BookService {
+
+ private AccommodationMapper accommodationMapper;
+ private FeePolicyMapper feePolicyMapper;
+ private BookingMapper bookingMapper;
+
+ public BookService(AccommodationMapper accommodationMapper,
+ FeePolicyMapper feePolicyMapper,
+ BookingMapper bookingMapper) {
+ this.accommodationMapper = accommodationMapper;
+ this.feePolicyMapper = feePolicyMapper;
+ this.bookingMapper = bookingMapper;
+ }
+
+ public AccommodationDTO getAccommodation(Integer id, Filter filter) {
+ if(accommodationMapper.countById(id) == 0) {
+ throw new EntityNotFoundException(ErrorMessage.ENTITY_NOT_FOUND.getMessage());
+ }
+
+ Map<String, Object> parameters = DAOUtils.createParameters(filter, id);
+ Accommodation accommodation = accommodationMapper.findAccommodationChargeInfoById(parameters);
+
+ float accommodationTaxRate = feePolicyMapper.findAccommodationTax();
+
+ return new AccommodationDTO.Builder(accommodation.getId())
+ .pricePerNight(accommodation.getOriginalPricePerNight())
+ .pricePerNightDiscounted(accommodation.getDiscountedPricePerNight())
+ .priceDuringPeriod(accommodation.getPriceDuringPeriod(filter))
+ .cleaningFee(accommodation.getCleaningFee())
+ .serviceTax(accommodation.getServiceTax(filter))
+ .accommodationTax(accommodation.getAccommodationTax(filter, accommodationTaxRate))
+ .totalPrice(accommodation.getTotalPrice(filter, accommodationTaxRate))
+ .build();
+ }
+
+ public boolean booking(Integer id, Filter filter, User user) {
+ if(accommodationMapper.countById(id) == 0) {
+ throw new EntityNotFoundException(ErrorMessage.ENTITY_NOT_FOUND.getMessage());
+ }
+
+ Booking newBooking = new Booking(user, id, filter);
+
+ if (bookingMapper.countByAccommodationIdAndPeriod(newBooking) > 0) {
+ return false;
+ }
+ bookingMapper.insertBooking(newBooking);
+ return true;
+ }
+} | Java | ๋ฉ์๋ ์ด๋ฆ์ ์กฐ๊ธ ๋ ์ง๊ด์ ์ผ๋ก ๋ฐ๊ฟ์ฃผ์ธ์.
`insertNewBooking` ์ด๋์ง `saveNewBooking` ์ด๋์ง.... |
@@ -0,0 +1,97 @@
+package com.codesquad.airbnb.business;
+
+import com.codesquad.airbnb.common.security.GithubToken;
+import com.codesquad.airbnb.common.utils.JWTUtils;
+import com.codesquad.airbnb.dao.UserMapper;
+import com.codesquad.airbnb.domain.model.User;
+import com.fasterxml.jackson.databind.JsonNode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.*;
+import org.springframework.stereotype.Service;
+import org.springframework.web.client.RestTemplate;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+
+@Service
+public class LoginService {
+
+ private static final Logger log = LoggerFactory.getLogger(LoginService.class);
+
+ private UserMapper userMapper;
+
+ @Value("${github.oauth.client.id}")
+ private String CLIENTID;
+
+ @Value("${github.oauth.client.secret}")
+ private String CLIENTSECRET;
+
+ @Value("${github.oauth.access_token.uri}")
+ private String GITHUB_ACCESS_TOKEN_URI;
+
+ @Value("${github.oauth.scope.user.email.uri}")
+ private String GITHUB_USER_EMAIL_URI;
+
+ private static final String JWT_PAYLOAD = "email";
+
+ public LoginService(UserMapper userMapper) {
+ this.userMapper = userMapper;
+ }
+
+ public String parseJWTFromGithubAccount(String code) {
+ GithubToken githubToken = getAccessToken(code);
+ User loginUser = new User(getUserEmailFromOAuthToken(githubToken));
+ saveUserIfNotExist(loginUser);
+ return parseJWTByUser(loginUser);
+ }
+
+ public User getUserFromJWT(String token) {
+ User loginUser = new User(JWTUtils.getStringFromJWT(JWT_PAYLOAD, token));
+ loginUser = userMapper.findByEmail(loginUser);
+
+ log.debug("logined User: {}", loginUser);
+
+ return loginUser;
+ }
+
+ private GithubToken getAccessToken(String code) {
+ HttpHeaders headers = new HttpHeaders();
+ headers.setContentType(MediaType.APPLICATION_JSON);
+
+ Map<String, String> payload = new HashMap<>();
+ payload.put("code", code);
+ payload.put("client_id", CLIENTID);
+ payload.put("client_secret", CLIENTSECRET);
+
+ ResponseEntity<GithubToken> response = new RestTemplate().postForEntity(GITHUB_ACCESS_TOKEN_URI,
+ new HttpEntity<>(payload, headers),
+ GithubToken.class);
+
+ return response.getBody();
+ }
+
+ private String getUserEmailFromOAuthToken(GithubToken githubToken) {
+ HttpHeaders headers = new HttpHeaders();
+ headers.setBearerAuth(githubToken.getAccessToken());
+
+ ResponseEntity<JsonNode> response = new RestTemplate().exchange(GITHUB_USER_EMAIL_URI,
+ HttpMethod.GET,
+ new HttpEntity<>(headers),
+ JsonNode.class);
+
+ return Objects.requireNonNull(response.getBody()).findValue("email").asText();
+ }
+
+ private void saveUserIfNotExist(User loginUser) {
+ if (userMapper.findByEmail(loginUser) == null) {
+ userMapper.insertUser(loginUser);
+ }
+ }
+
+ private String parseJWTByUser(User user) {
+ return JWTUtils.createTokenByString(JWT_PAYLOAD, user.getEmail());
+ }
+} | Java | ์์์ ์ฑ๊ฒฉ์ ์ง๋๊ณ ์๊ธด ํ์ง๋ง ์ฌ๊ธฐ์ ๋ถ๋ช
ํ ์ธ์คํด์ค ๋ณ์์ด๋ฏ๋ก,
์นด๋ฉ ์ผ์ด์ค๋ก ์์ฑํ๋ ๊ฒ์ด ๋ง์ต๋๋ค. |
@@ -0,0 +1,6 @@
+package com.codesquad.airbnb.common.utils;
+
+public class CurrencyConvertor {
+
+ public static final float EXCHANGE_RATE_FROM_USD_TO_KRW = 1231.54f;
+} | Java | ํธ์ค์ค.... ํ์จ์ด ์ธ์ ์ด๋ ๊ฒ ์ฌ๋์ฃ |
@@ -0,0 +1,13 @@
+package com.codesquad.airbnb.common.utils;
+
+import org.springframework.validation.BindingResult;
+import org.springframework.validation.ObjectError;
+
+import java.util.stream.Collectors;
+
+public class CustomValidatorUtils {
+
+ public static String getErrorMessage(BindingResult result) {
+ return result.getAllErrors().stream().map(ObjectError::getCode).collect(Collectors.joining(", "));
+ }
+} | Java | `Collectors.joining` ํ์ฉ ์ข์ต๋๋ค! |
@@ -0,0 +1,16 @@
+package com.codesquad.airbnb.domain.model;
+
+public class City {
+
+ private Integer id;
+
+ private String name;
+
+ private String country;
+
+ public City() {}
+
+ public String getName() {
+ return name;
+ }
+} | Java | ๊ธฐ๋ณธ์์ฑ์ ์ฌ์ฉ ์ข์ต๋๋ค.
๊ทธ๋ฌ๋ ๊ฐ ํ๋๋ค์ ์ด๊ธฐํํด์ค ํ์๋ ์ ํ ์๋์? |
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+ <component name="DataSourceManagerImpl" format="xml" multifile-model="true">
+ <data-source source="LOCAL" name="baseball-10" uuid="873ec135-86e5-491d-a981-98740f2170c3">
+ <driver-ref>mysql</driver-ref>
+ <synchronize>true</synchronize>
+ <jdbc-driver>com.mysql.jdbc.Driver</jdbc-driver>
+ <jdbc-url>jdbc:mysql://baseball-10-proeject.csjhbz8c8oyh.ap-northeast-2.rds.amazonaws.com:3306</jdbc-url>
+ </data-source>
+ <data-source source="LOCAL" name="baseball-10-real" uuid="24139289-bb1d-4da5-b58f-bd3fb57713eb">
+ <driver-ref>mysql.8</driver-ref>
+ <synchronize>true</synchronize>
+ <jdbc-driver>com.mysql.cj.jdbc.Driver</jdbc-driver>
+ <jdbc-url>jdbc:mysql://baseball-10-rds.csjhbz8c8oyh.ap-northeast-2.rds.amazonaws.com:3306</jdbc-url>
+ </data-source>
+ </component>
+</project>
\ No newline at end of file | Unknown | ์ธํ
๋ฆฌ์ ์ด Datasource ๊ธฐ๋ฅ ์ฌ์ฉํด๋ณด์ ๊ฒ ์ข๋ค์. |
@@ -0,0 +1,21 @@
+# Getting Started
+
+### Reference Documentation
+For further reference, please consider the following sections:
+
+* [Official Gradle documentation](https://docs.gradle.org)
+* [Spring Boot Gradle Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/2.2.6.RELEASE/gradle-plugin/reference/html/)
+* [Spring Web](https://docs.spring.io/spring-boot/docs/2.2.6.RELEASE/reference/htmlsingle/#boot-features-developing-web-applications)
+
+### Guides
+The following guides illustrate how to use some features concretely:
+
+* [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/)
+* [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/)
+* [Building REST services with Spring](https://spring.io/guides/tutorials/bookmarks/)
+
+### Additional Links
+These additional references should also help you:
+
+* [Gradle Build Scans โ insights for your project's build](https://scans.gradle.com#gradle)
+ | Unknown | ๊ธฐ๋ณธ ์์ฑ๋ ๋งํฌ๋ค์ด ํ์ผ์ ๊ณผ๊ฐํ ๋ ๋ ค์ฃผ์ธ์. |
@@ -0,0 +1,65 @@
+import InputView from './view/InputView.js';
+import OutputView from './view/OutputView.js';
+import Service from './Service.js';
+import { print } from './utils/missionUtils.js';
+
+class Controller {
+ constructor() {
+ this.service = new Service();
+ }
+
+ async run() {
+ await this.inputControl();
+
+ const totalPrice = this.service.totalOrderPrice();
+ const BenefitDetails = this.service.BenefitsDetails();
+ const totalBenefitPrice = this.service.totalBenefitsPrice();
+ const badge = this.service.calculateBadge();
+
+ OutputView.printTotalPriceAndGift(totalPrice);
+ OutputView.printBenefits(totalPrice, BenefitDetails, totalBenefitPrice);
+ OutputView.printTotalBenefitAmount(totalPrice, totalBenefitPrice);
+ OutputView.printEstimatedAmount(this.service.calculatePayment());
+ OutputView.printBadge(badge);
+ }
+
+ async inputControl() {
+ OutputView.printWelcome();
+ const date = await this.#inputDate();
+ const order = await this.#inputOrder();
+ OutputView.printGuide(date);
+ OutputView.printMenu(order);
+ }
+
+ async #inputDate() {
+ let date;
+
+ while (!date) {
+ try {
+ const getDate = await InputView.readDate();
+ date = this.service.benefitsCreate(getDate);
+ } catch (error) {
+ print(error.message);
+ }
+ }
+
+ return date;
+ }
+
+ async #inputOrder() {
+ let order;
+
+ while (!order) {
+ try {
+ const getOrder = await InputView.readMenu();
+ order = this.service.orderMenuCreate(getOrder);
+ } catch (error) {
+ print(error.message);
+ }
+ }
+
+ return order;
+ }
+}
+
+export default Controller; | JavaScript | ์ ๊ทผ์ ํ์ ๋์ง ์์ผ์ ์ด์ ๊ฐ ์์ผ์ค๊น์? |
@@ -0,0 +1,113 @@
+import Benefits from './domain/Benefits.js';
+import OrderMenu from './domain/OrderMenu.js';
+import {
+ BENEFITS_THRESHOLD,
+ GIFT_THRESHOLD,
+ MENU_PRICE,
+} from './utils/constants.js';
+
+const BADGE = {
+ ์ฐํ: 20000,
+ ํธ๋ฆฌ: 10000,
+ ๋ณ: 5000,
+};
+
+class Service {
+ #benefits;
+
+ #orderMenu;
+
+ benefitsCreate(date) {
+ this.#benefits = new Benefits(date);
+ return date;
+ }
+
+ orderMenuCreate(order) {
+ this.#orderMenu = new OrderMenu(order);
+ return order;
+ }
+
+ totalOrderPrice() {
+ const price = this.#orderMenu.totalOrderAmount();
+ return price;
+ }
+
+ // ํํ ๋ด์ญ
+ BenefitsDetails() {
+ const dessertCount = this.#orderMenu.dessertCount();
+ const mainCount = this.#orderMenu.mainCount();
+ const benefitsArray = [
+ [
+ this.#benefits.christmasDiscount(),
+ this.#benefits.weekdayDiscount(dessertCount),
+ this.#benefits.weekendDiscount(mainCount),
+ this.#benefits.specialDiscount(),
+ ],
+ [this.#giftEvent()],
+ ];
+
+ return benefitsArray;
+ }
+
+ // ์ฆ์ ์ด๋ฒคํธ
+ #giftEvent() {
+ let giftDiscount = 0;
+
+ if (this.totalOrderPrice() >= GIFT_THRESHOLD) {
+ giftDiscount += MENU_PRICE.์ดํ์ธ;
+ }
+ return ['์ฆ์ ์ด๋ฒคํธ', giftDiscount];
+ }
+
+ // ์ด ํํ๊ธ์ก
+ totalBenefitsPrice() {
+ const BenefitsDetails = this.BenefitsDetails();
+
+ const totalBenefitsPrice = BenefitsDetails.reduce(
+ (acc, innerArray) =>
+ acc +
+ innerArray.reduce(
+ (total, [, discountAmount]) => total + discountAmount,
+ 0,
+ ),
+ 0,
+ );
+
+ return totalBenefitsPrice;
+ }
+
+ // ์์ ๊ฒฐ์ ๊ธ์ก
+ calculatePayment() {
+ const totalPrice = this.totalOrderPrice();
+ const totalBenefitPrice = this.totalBenefitsPrice();
+
+ if (totalPrice < BENEFITS_THRESHOLD) {
+ return totalPrice;
+ }
+
+ return this.calculateEstimatedAmount(totalPrice, totalBenefitPrice);
+ }
+
+ calculateEstimatedAmount(totalPrice, totalBenefitPrice) {
+ if (totalPrice >= GIFT_THRESHOLD) {
+ const benefitPrice = totalBenefitPrice - MENU_PRICE.์ดํ์ธ;
+ const payment = totalPrice - benefitPrice;
+ return payment;
+ }
+
+ const payment = totalPrice - totalBenefitPrice;
+ return payment;
+ }
+
+ calculateBadge() {
+ const totalBenefitPrice = this.totalBenefitsPrice();
+
+ const badge = Object.keys(BADGE).find(
+ (key) => totalBenefitPrice >= BADGE[key],
+ );
+
+ return badge;
+ }
+}
+
+export default Service; | JavaScript | innerArray๋ณด๋ค ๋ค๋ฅธ ๋ณ์๋ช
์ผ๋ก ๋ฌด์จ ๊ฐ์ ์๋ฏธํ๋์ง ๋ํ๋ด์ฃผ์๋ฉด ์ข์ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,8 @@
+import { MissionUtils } from '@woowacourse/mission-utils';
+
+export const readLineAsync = async (query) => {
+ const input = await MissionUtils.Console.readLineAsync(query);
+ return input;
+};
+
+export const print = (message) => MissionUtils.Console.print(message); | JavaScript | ๊ตฌ์กฐ๋ถํด ํ ๋น์ผ๋ก Console๋ก๋ง ์ฒ๋ฆฌํด๋ ๋์ง ์๋์? |
@@ -0,0 +1,104 @@
+import { print } from '../utils/missionUtils.js';
+import {
+ GIFT_THRESHOLD,
+ BENEFITS_THRESHOLD,
+ MENU_PRICE,
+} from '../utils/constants.js';
+
+const OutputView = {
+ printWelcome() {
+ print('์๋
ํ์ธ์! ์ฐํ
์ฝ ์๋น 12์ ์ด๋ฒคํธ ํ๋๋์
๋๋ค.');
+ },
+
+ printGuide(date) {
+ print(`12์ ${date}์ผ์ ์ฐํ
์ฝ ์๋น์์ ๋ฐ์ ์ด๋ฒคํธ ํํ ๋ฏธ๋ฆฌ ๋ณด๊ธฐ!`);
+ },
+
+ printMenu(order) {
+ const dividedOrder = order.split(',');
+ const orderArray = dividedOrder.map((value) => {
+ const [menuName, count] = value.split('-');
+ return [menuName, count];
+ });
+
+ print('\n<์ฃผ๋ฌธ ๋ฉ๋ด>');
+ orderArray.forEach((item) => {
+ const [menuName, count] = item;
+ print(`${menuName} ${count}๊ฐ`);
+ });
+ },
+
+ printTotalPriceAndGift(price) {
+ const showPrice = price.toLocaleString();
+
+ print('\n<ํ ์ธ ์ ์ด์ฃผ๋ฌธ ๊ธ์ก>');
+ print(`${showPrice}์`);
+ print('\n<์ฆ์ ๋ฉ๋ด>');
+
+ if (price >= GIFT_THRESHOLD) {
+ print('์ดํ์ธ 1๊ฐ');
+ } else {
+ print('์์');
+ }
+ },
+
+ printBenefits(price, benefitsArray, totalBenefitPrice) {
+ print('\n<ํํ ๋ด์ญ>');
+
+ if (price < BENEFITS_THRESHOLD) {
+ print('์์');
+ return;
+ }
+
+ this.dateBenefits(benefitsArray);
+
+ if (totalBenefitPrice === 0) {
+ print('์์');
+ }
+ },
+
+ dateBenefits(benefitsArray) {
+ benefitsArray.forEach((dateBenefits) => {
+ dateBenefits.forEach((giftBenefit) => {
+ const [eventName, discount] = giftBenefit;
+ const showDiscount = discount.toLocaleString();
+ if (discount !== 0) {
+ print(`${eventName}: -${showDiscount}์`);
+ }
+ });
+ });
+ },
+
+ printTotalBenefitAmount(totalPrice, totalBenefitPrice) {
+ const showTotalDiscount = totalBenefitPrice.toLocaleString();
+
+ print('\n<์ดํํ ๊ธ์ก>');
+
+ if (totalBenefitPrice === 0 || totalPrice < BENEFITS_THRESHOLD) {
+ print('0์');
+ }
+
+ if (totalBenefitPrice !== 0 && totalPrice >= BENEFITS_THRESHOLD) {
+ print(`-${showTotalDiscount}์`);
+ }
+ },
+
+ printEstimatedAmount(payment) {
+ const estimatedAmount = payment.toLocaleString();
+
+ print('\n<ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก>');
+ print(estimatedAmount);
+ },
+
+ printBadge(calculateBadge) {
+ print('\n<12์ ์ด๋ฒคํธ ๋ฐฐ์ง>');
+
+ if (calculateBadge === undefined) {
+ print('์์');
+ return;
+ }
+ print(calculateBadge);
+ },
+};
+
+export default OutputView; | JavaScript | ๋ณ์๋ช
์ ์๋ฃํ์ ๋ฃ๋ ๊ฒ ์ข์ง ์๋ค๊ณ ๋ค์์ด์.
orders์ ๊ฐ์ด ๋ณต์ํํ์ผ๋ก ๋ฐ๊พธ์ด ์ฃผ์๋ฉด ์ข์ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,115 @@
+import OrderMenu from '../domain/OrderMenu.js';
+
+describe('์ฃผ๋ฌธ ๋ฉ๋ด ๊ฒ์ฆ ํ
์คํธ', () => {
+ const orderMenuTestCase = [
+ {
+ testName: '์ฃผ๋ฌธ ํ์์ด ์์์ ๋ค๋ฅด๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.',
+ input: '์์ก์ด์ํ 1๊ฐ, ์ด์ฝ์ผ์ดํฌ 2๊ฐ',
+ },
+ {
+ testName: '๋ฉ๋ดํ์ ์๋ ๋ฉ๋ด๊ฐ ์์ผ๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.',
+ input: 'ํฐ๋ณธ์คํ
์ดํฌ-1,๋ง๋ผํ-1',
+ },
+ {
+ testName: '์ฃผ๋ฌธ ์๋์ด 1 ๋ฏธ๋ง์ด๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.',
+ input: 'ํด์ฐ๋ฌผํ์คํ-0,์ ๋ก์ฝ๋ผ-1',
+ },
+ {
+ testName: '์ฃผ๋ฌธ ์๋์ ์ดํฉ์ด 20์ด ๋์ผ๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.',
+ input: '์์ ์๋ฌ๋-14,๋ฐ๋นํ๋ฆฝ-5,ํํ์ค-2',
+ },
+ {
+ testName: '์ค๋ณต๋ ๋ฉ๋ด๊ฐ ์์ผ๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.',
+ input: '๋ฐ๋นํ๋ฆฝ-2,๋ ๋์์ธ-1,๋ฐ๋นํ๋ฆฝ-1',
+ },
+ ];
+
+ orderMenuTestCase.forEach((testCase) => {
+ test(testCase.testName, () => {
+ expect(() => {
+ new OrderMenu(testCase.input);
+ }).toThrow('[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ });
+ });
+
+ test('์๋ฃ๋ง ์ฃผ๋ฌธํ๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.', () => {
+ expect(() => {
+ new OrderMenu('์ ๋ก์ฝ๋ผ-5,๋ ๋์์ธ-2,์ดํ์ธ-3');
+ }).toThrow('[ERROR] ์๋ฃ๋ง ์ฃผ๋ฌธํ ์ ์์ต๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ });
+});
+
+describe('์ํ๊ฐ ํ์ฉ ํ
์คํธ', () => {
+ test('์๋๊ณผ ๊ฐ๊ฒฉ์ ๊ณฑํด์ ์ด ์ฃผ๋ฌธ๊ธ์ก์ ๊ณ์ฐํ๋ค.', () => {
+ const orderMenuTestCase = [
+ {
+ input: 'ํด์ฐ๋ฌผํ์คํ-3,์์ก์ด์ํ-1,ํํ์ค-2,์ ๋ก์ฝ๋ผ-4',
+ result: 134000,
+ },
+ {
+ input: '๋ฐ๋นํ๋ฆฝ-5,์์ ์๋ฌ๋-3,๋ ๋์์ธ-2,์์ด์คํฌ๋ฆผ-5',
+ result: 439000,
+ },
+ {
+ input:
+ 'ํฐ๋ณธ์คํ
์ดํฌ-2,ํด์ฐ๋ฌผํ์คํ-1,ํฌ๋ฆฌ์ค๋ง์คํ์คํ-10,์ด์ฝ์ผ์ดํฌ-3,์ดํ์ธ-4',
+ result: 540000,
+ },
+ ];
+
+ orderMenuTestCase.forEach((testCase) => {
+ // given
+ const orderMenu = new OrderMenu(testCase.input);
+
+ // when
+ const received = orderMenu.totalOrderAmount();
+
+ // then
+ expect(received).toBe(testCase.result);
+ });
+ });
+
+ test('๋์ ํธ ๋ฉ๋ด์ ์ฃผ๋ฌธ ๊ฐ์๋ฅผ ๊ณ์ฐํ๋ค.', () => {
+ const orderMenuTestCase = [
+ { input: '๋ฐ๋นํ๋ฆฝ-1,์ด์ฝ์ผ์ดํฌ-9,์ ๋ก์ฝ๋ผ-2,์์ด์คํฌ๋ฆผ-3', result: 12 },
+ { input: 'ํฌ๋ฆฌ์ค๋ง์คํ์คํ-3,ํฐ๋ณธ์คํ
์ดํฌ-5,๋ ๋์์ธ-1', result: 0 },
+ {
+ input: '์์ก์ด์ํ-2,์์ ์๋ฌ๋-5,ํด์ฐ๋ฌผํ์คํ-3,์ด์ฝ์ผ์ดํฌ-1',
+ result: 1,
+ },
+ ];
+
+ orderMenuTestCase.forEach((testCase) => {
+ // given
+ const orderMenu = new OrderMenu(testCase.input);
+
+ // when
+ const received = orderMenu.dessertCount();
+
+ // then
+ expect(received).toBe(testCase.result);
+ });
+ });
+
+ test('๋ฉ์ธ ๋ฉ๋ด์ ์ฃผ๋ฌธ ๊ฐ์๋ฅผ ๊ณ์ฐํ๋ค.', () => {
+ const orderMenuTestCase = [
+ {
+ input: 'ํฐ๋ณธ์คํ
์ดํฌ-2,์์ก์ด์ํ-1,์์ ์๋ฌ๋-1,ํด์ฐ๋ฌผํ์คํ-4',
+ result: 6,
+ },
+ { input: 'ํํ์ค-7,ํฌ๋ฆฌ์ค๋ง์คํ์คํ-4,๋ ๋์์ธ-1', result: 4 },
+ { input: '์์ก์ด์ํ-2,์ ๋ก์ฝ๋ผ-4,์ด์ฝ์ผ์ดํฌ-13', result: 0 },
+ ];
+
+ orderMenuTestCase.forEach((testCase) => {
+ // given
+ const orderMenu = new OrderMenu(testCase.input);
+
+ // when
+ const received = orderMenu.mainCount();
+
+ // then
+ expect(received).toBe(testCase.result);
+ });
+ });
+}); | JavaScript | test.each()๋ฅผ ์ฌ์ฉํ์ง ์๊ณ ์ด๋ ๊ฒ ์ฒ๋ฆฌํ์ ์ด์ ๊ฐ ์์ผ์ค๊น์? |
@@ -0,0 +1,126 @@
+import { MENU_PRICE } from '../utils/constants.js';
+
+const MENU_TYPES = Object.freeze({
+ appetizer: ['์์ก์ด์ํ', 'ํํ์ค', '์์ ์๋ฌ๋'],
+ main: ['ํฐ๋ณธ์คํ
์ดํฌ', '๋ฐ๋นํ๋ฆฝ', 'ํด์ฐ๋ฌผํ์คํ', 'ํฌ๋ฆฌ์ค๋ง์คํ์คํ'],
+ dessert: ['์ด์ฝ์ผ์ดํฌ', '์์ด์คํฌ๋ฆผ'],
+ drink: ['์ ๋ก์ฝ๋ผ', '๋ ๋์์ธ', '์ดํ์ธ'],
+});
+
+const LIMIT_NUMBER = Object.freeze({
+ minNumber: 1,
+ maxNumber: 20,
+});
+
+class OrderMenu {
+ #orderMenu;
+
+ constructor(order) {
+ this.#validateFormat(order); // ์
๋ ฅ ํ์ ๊ฒ์ฆ
+ this.#arrayMenu(order); // ๊ฐ๊ฒฉ๊ณผ ํจ๊ป ๋ฐฐ์ด ๊ฐ์ฒด ์ ์ฅ
+ this.#validateMenuItems(); // ๋ฉ๋ด ์ ๋ฌด ๊ฒ์ฆ
+ this.#validateCount(); // ์ฃผ๋ฌธ ๊ฐ์ ๊ฒ์ฆ
+ this.#validateTotalCount(); // ์ฃผ๋ฌธ ์ด๊ฐ์ ๊ฒ์ฆ
+ this.#validateDuplicateMenu(); // ๋ฉ๋ด ์ค๋ณต ๊ฒ์ฆ
+ this.#validateOnlyDrink(); // ์๋ฃ๋ง ์ฃผ๋ฌธ ๊ฒ์ฆ
+ }
+
+ #arrayMenu(order) {
+ const menuItem = order.split(',');
+ this.#orderMenu = menuItem.map((item) => {
+ const [menuName, count] = item.split('-');
+ const price = MENU_PRICE[menuName] || 0;
+ const type = Object.keys(MENU_TYPES).find((category) =>
+ MENU_TYPES[category].includes(menuName),
+ );
+ return { menuName, count: Number(count), price, type };
+ });
+ }
+
+ #validateFormat(order) {
+ const regex = /^([๊ฐ-ํฃ]+-\d+,)*[๊ฐ-ํฃ]+-\d+$/;
+ const testResult = regex.test(order);
+
+ if (testResult === false) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #validateMenuItems() {
+ const result = this.#orderMenu.some((item) => item.price === 0);
+
+ if (result) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #validateCount() {
+ this.#orderMenu.forEach((menu) => {
+ if (menu.count < LIMIT_NUMBER.minNumber) {
+ throw new Error(
+ '[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.',
+ );
+ }
+ });
+ }
+
+ #validateTotalCount() {
+ const totalCount = this.#orderMenu.reduce(
+ (sum, item) => sum + item.count,
+ 0,
+ );
+
+ if (totalCount > LIMIT_NUMBER.maxNumber) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #validateDuplicateMenu() {
+ const menuNameSet = new Set(this.#orderMenu.map((item) => item.menuName));
+
+ if (menuNameSet.size !== this.#orderMenu.length) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #validateOnlyDrink() {
+ const drinkMenu = MENU_TYPES.drink;
+ const result = this.#orderMenu.every((item) =>
+ drinkMenu.includes(item.menuName),
+ );
+
+ if (result) {
+ throw new Error('[ERROR] ์๋ฃ๋ง ์ฃผ๋ฌธํ ์ ์์ต๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ // ์ด ์ฃผ๋ฌธ๊ธ์ก
+ totalOrderAmount() {
+ const totalAmount = this.#orderMenu.reduce(
+ (sum, item) => sum + item.price * item.count,
+ 0,
+ );
+
+ return totalAmount;
+ }
+
+ // ๋์ ํธ ๋ฉ๋ด ๊ฐ์
+ dessertCount() {
+ const dessertMenu = this.#orderMenu.filter(
+ (item) => item.type === 'dessert',
+ );
+ const count = dessertMenu.reduce((total, item) => total + item.count, 0);
+
+ return count;
+ }
+
+ // ๋ฉ์ธ ๋ฉ๋ด ๊ฐ์
+ mainCount() {
+ const mainMenu = this.#orderMenu.filter((item) => item.type === 'main');
+ const count = mainMenu.reduce((total, item) => total + item.count, 0);
+
+ return count;
+ }
+}
+
+export default OrderMenu; | JavaScript | ์ด ๋ถ๋ถ๋ ์ฌ๊ธฐ์ ๋์ ์ด์ ๊ฐ ๋ฐ๋ก ์์ผ์ ์ง ๊ถ๊ธํ๋ค์..! |
@@ -0,0 +1,88 @@
+const DATE = Object.freeze({
+ eventEndDay: 31,
+ christmasEndDay: 25,
+});
+
+const WEEKDAY = Object.freeze([
+ 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 17, 18, 19, 20, 21, 24, 25, 26, 27, 28, 31,
+]);
+
+const WEEKEND = Object.freeze([1, 2, 8, 9, 15, 16, 22, 23, 29, 30]);
+
+const SPECIAL = Object.freeze([3, 10, 17, 24, 25, 31]);
+
+class Benefits {
+ #date;
+
+ constructor(date) {
+ this.#validateNumber(date); // ์์ฐ์ ๊ฒ์ฆ
+ this.#date = Number(date);
+ this.#validateDate(); // ๋ ์ง ๋ฒ์ ๊ฒ์ฆ
+ }
+
+ #validateNumber(date) {
+ const regex = /^[1-9]\d*$/;
+ const testResult = regex.test(date);
+
+ if (testResult === false) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #validateDate() {
+ if (this.#date > DATE.eventEndDay) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ // ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ
+ christmasDiscount() {
+ const START_PRICE = 1000;
+ const INCREASE_PRICE = 100;
+ let discountedAmount = 0;
+
+ if (this.#date <= DATE.christmasEndDay) {
+ discountedAmount = START_PRICE + (this.#date - 1) * INCREASE_PRICE;
+ }
+
+ return ['ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ', discountedAmount];
+ }
+
+ // ํ์ผ ํ ์ธ
+ weekdayDiscount(dessertCount) {
+ const WEEKDAY_DISCOUNT = 2023;
+ let discountedAmount = 0;
+
+ if (WEEKDAY.includes(this.#date)) {
+ discountedAmount = WEEKDAY_DISCOUNT * dessertCount;
+ }
+
+ return ['ํ์ผ ํ ์ธ', discountedAmount];
+ }
+
+ // ์ฃผ๋ง ํ ์ธ
+ weekendDiscount(mainCount) {
+ const WEEKEND_DISCOUNT = 2023;
+ let discountedAmount = 0;
+
+ if (WEEKEND.includes(this.#date)) {
+ discountedAmount = WEEKEND_DISCOUNT * mainCount;
+ }
+
+ return ['์ฃผ๋ง ํ ์ธ', discountedAmount];
+ }
+
+ // ํน๋ณ ํ ์ธ
+ specialDiscount() {
+ const DISCOUNT_PRICE = 1000;
+ let discountedAmount = 0;
+
+ if (SPECIAL.includes(this.#date)) {
+ discountedAmount = DISCOUNT_PRICE;
+ }
+
+ return ['ํน๋ณ ํ ์ธ', discountedAmount];
+ }
+}
+
+export default Benefits; | JavaScript | DATE.eventEndDay ์์์ฒ๋ฆฌํํ์ ๋ถ๋ถ์ด ์ธ์๊น๋ค์:) |
@@ -0,0 +1,88 @@
+const DATE = Object.freeze({
+ eventEndDay: 31,
+ christmasEndDay: 25,
+});
+
+const WEEKDAY = Object.freeze([
+ 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 17, 18, 19, 20, 21, 24, 25, 26, 27, 28, 31,
+]);
+
+const WEEKEND = Object.freeze([1, 2, 8, 9, 15, 16, 22, 23, 29, 30]);
+
+const SPECIAL = Object.freeze([3, 10, 17, 24, 25, 31]);
+
+class Benefits {
+ #date;
+
+ constructor(date) {
+ this.#validateNumber(date); // ์์ฐ์ ๊ฒ์ฆ
+ this.#date = Number(date);
+ this.#validateDate(); // ๋ ์ง ๋ฒ์ ๊ฒ์ฆ
+ }
+
+ #validateNumber(date) {
+ const regex = /^[1-9]\d*$/;
+ const testResult = regex.test(date);
+
+ if (testResult === false) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #validateDate() {
+ if (this.#date > DATE.eventEndDay) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ // ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ
+ christmasDiscount() {
+ const START_PRICE = 1000;
+ const INCREASE_PRICE = 100;
+ let discountedAmount = 0;
+
+ if (this.#date <= DATE.christmasEndDay) {
+ discountedAmount = START_PRICE + (this.#date - 1) * INCREASE_PRICE;
+ }
+
+ return ['ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ', discountedAmount];
+ }
+
+ // ํ์ผ ํ ์ธ
+ weekdayDiscount(dessertCount) {
+ const WEEKDAY_DISCOUNT = 2023;
+ let discountedAmount = 0;
+
+ if (WEEKDAY.includes(this.#date)) {
+ discountedAmount = WEEKDAY_DISCOUNT * dessertCount;
+ }
+
+ return ['ํ์ผ ํ ์ธ', discountedAmount];
+ }
+
+ // ์ฃผ๋ง ํ ์ธ
+ weekendDiscount(mainCount) {
+ const WEEKEND_DISCOUNT = 2023;
+ let discountedAmount = 0;
+
+ if (WEEKEND.includes(this.#date)) {
+ discountedAmount = WEEKEND_DISCOUNT * mainCount;
+ }
+
+ return ['์ฃผ๋ง ํ ์ธ', discountedAmount];
+ }
+
+ // ํน๋ณ ํ ์ธ
+ specialDiscount() {
+ const DISCOUNT_PRICE = 1000;
+ let discountedAmount = 0;
+
+ if (SPECIAL.includes(this.#date)) {
+ discountedAmount = DISCOUNT_PRICE;
+ }
+
+ return ['ํน๋ณ ํ ์ธ', discountedAmount];
+ }
+}
+
+export default Benefits; | JavaScript | ํ์ผ์ ๋ํ ๋ ์ง๋ฅผ ์ง์ ์์ฑ ๋ฐ ์์์ฒ๋ฆฌํ์
์ WEEKDAY ๊ฐ์ฒด์์ ํด๋น ๋ ์ง๊ฐ ํฌํจ๋๋ ์ง๋ฅผ ๋น๊ตํ ๋ก์ง์ผ๋ก ์์๋ฉ๋๋ค.
๋ง์ฝ 2023๋
12์์ด๋ผ๋ ๋ฒ์์ ๊ฐ์ด ๋ณ๊ฒฝ์ด ๋๋ค๋ฉด (2024๋
1์์ ํ์ผ,2024๋
4์์ ํ์ผ ๋ฑ) ๋งค๋ฒ ๋ ์ง๋ฅผ ํ์ผ์ธ์ง ํ์ธํด ์ง์ ์ฒ๋ฆฌํด์ผ ํจ์ผ๋ก ํ์ฅ์ฑ์ ์ด๋ ค์์ด ์๊ธธ ๊ฒ ๊ฐ์์.
js ์์ ์ ๊ณตํ๋ ๋ด์ฅ ๊ฐ์ฒด Date ๋ฅผ ํ์ฉํด ํ์ผ์ ๊ตฌํ๋ ๋ฉ์๋๋ฅผ ํ์ฉํ๋ ๊ฑด ์ด๋ ์ ๊ฐ์? |
@@ -0,0 +1,88 @@
+const DATE = Object.freeze({
+ eventEndDay: 31,
+ christmasEndDay: 25,
+});
+
+const WEEKDAY = Object.freeze([
+ 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 17, 18, 19, 20, 21, 24, 25, 26, 27, 28, 31,
+]);
+
+const WEEKEND = Object.freeze([1, 2, 8, 9, 15, 16, 22, 23, 29, 30]);
+
+const SPECIAL = Object.freeze([3, 10, 17, 24, 25, 31]);
+
+class Benefits {
+ #date;
+
+ constructor(date) {
+ this.#validateNumber(date); // ์์ฐ์ ๊ฒ์ฆ
+ this.#date = Number(date);
+ this.#validateDate(); // ๋ ์ง ๋ฒ์ ๊ฒ์ฆ
+ }
+
+ #validateNumber(date) {
+ const regex = /^[1-9]\d*$/;
+ const testResult = regex.test(date);
+
+ if (testResult === false) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #validateDate() {
+ if (this.#date > DATE.eventEndDay) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ // ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ
+ christmasDiscount() {
+ const START_PRICE = 1000;
+ const INCREASE_PRICE = 100;
+ let discountedAmount = 0;
+
+ if (this.#date <= DATE.christmasEndDay) {
+ discountedAmount = START_PRICE + (this.#date - 1) * INCREASE_PRICE;
+ }
+
+ return ['ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ', discountedAmount];
+ }
+
+ // ํ์ผ ํ ์ธ
+ weekdayDiscount(dessertCount) {
+ const WEEKDAY_DISCOUNT = 2023;
+ let discountedAmount = 0;
+
+ if (WEEKDAY.includes(this.#date)) {
+ discountedAmount = WEEKDAY_DISCOUNT * dessertCount;
+ }
+
+ return ['ํ์ผ ํ ์ธ', discountedAmount];
+ }
+
+ // ์ฃผ๋ง ํ ์ธ
+ weekendDiscount(mainCount) {
+ const WEEKEND_DISCOUNT = 2023;
+ let discountedAmount = 0;
+
+ if (WEEKEND.includes(this.#date)) {
+ discountedAmount = WEEKEND_DISCOUNT * mainCount;
+ }
+
+ return ['์ฃผ๋ง ํ ์ธ', discountedAmount];
+ }
+
+ // ํน๋ณ ํ ์ธ
+ specialDiscount() {
+ const DISCOUNT_PRICE = 1000;
+ let discountedAmount = 0;
+
+ if (SPECIAL.includes(this.#date)) {
+ discountedAmount = DISCOUNT_PRICE;
+ }
+
+ return ['ํน๋ณ ํ ์ธ', discountedAmount];
+ }
+}
+
+export default Benefits; | JavaScript | ๋ก์ง์ ์ผ๊ด์ฑ์ด ๋์ ์ฝ๊ธฐ ๋งค์ฐ ํธํ๋ค์! |
@@ -0,0 +1,126 @@
+import { MENU_PRICE } from '../utils/constants.js';
+
+const MENU_TYPES = Object.freeze({
+ appetizer: ['์์ก์ด์ํ', 'ํํ์ค', '์์ ์๋ฌ๋'],
+ main: ['ํฐ๋ณธ์คํ
์ดํฌ', '๋ฐ๋นํ๋ฆฝ', 'ํด์ฐ๋ฌผํ์คํ', 'ํฌ๋ฆฌ์ค๋ง์คํ์คํ'],
+ dessert: ['์ด์ฝ์ผ์ดํฌ', '์์ด์คํฌ๋ฆผ'],
+ drink: ['์ ๋ก์ฝ๋ผ', '๋ ๋์์ธ', '์ดํ์ธ'],
+});
+
+const LIMIT_NUMBER = Object.freeze({
+ minNumber: 1,
+ maxNumber: 20,
+});
+
+class OrderMenu {
+ #orderMenu;
+
+ constructor(order) {
+ this.#validateFormat(order); // ์
๋ ฅ ํ์ ๊ฒ์ฆ
+ this.#arrayMenu(order); // ๊ฐ๊ฒฉ๊ณผ ํจ๊ป ๋ฐฐ์ด ๊ฐ์ฒด ์ ์ฅ
+ this.#validateMenuItems(); // ๋ฉ๋ด ์ ๋ฌด ๊ฒ์ฆ
+ this.#validateCount(); // ์ฃผ๋ฌธ ๊ฐ์ ๊ฒ์ฆ
+ this.#validateTotalCount(); // ์ฃผ๋ฌธ ์ด๊ฐ์ ๊ฒ์ฆ
+ this.#validateDuplicateMenu(); // ๋ฉ๋ด ์ค๋ณต ๊ฒ์ฆ
+ this.#validateOnlyDrink(); // ์๋ฃ๋ง ์ฃผ๋ฌธ ๊ฒ์ฆ
+ }
+
+ #arrayMenu(order) {
+ const menuItem = order.split(',');
+ this.#orderMenu = menuItem.map((item) => {
+ const [menuName, count] = item.split('-');
+ const price = MENU_PRICE[menuName] || 0;
+ const type = Object.keys(MENU_TYPES).find((category) =>
+ MENU_TYPES[category].includes(menuName),
+ );
+ return { menuName, count: Number(count), price, type };
+ });
+ }
+
+ #validateFormat(order) {
+ const regex = /^([๊ฐ-ํฃ]+-\d+,)*[๊ฐ-ํฃ]+-\d+$/;
+ const testResult = regex.test(order);
+
+ if (testResult === false) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #validateMenuItems() {
+ const result = this.#orderMenu.some((item) => item.price === 0);
+
+ if (result) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #validateCount() {
+ this.#orderMenu.forEach((menu) => {
+ if (menu.count < LIMIT_NUMBER.minNumber) {
+ throw new Error(
+ '[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.',
+ );
+ }
+ });
+ }
+
+ #validateTotalCount() {
+ const totalCount = this.#orderMenu.reduce(
+ (sum, item) => sum + item.count,
+ 0,
+ );
+
+ if (totalCount > LIMIT_NUMBER.maxNumber) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #validateDuplicateMenu() {
+ const menuNameSet = new Set(this.#orderMenu.map((item) => item.menuName));
+
+ if (menuNameSet.size !== this.#orderMenu.length) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #validateOnlyDrink() {
+ const drinkMenu = MENU_TYPES.drink;
+ const result = this.#orderMenu.every((item) =>
+ drinkMenu.includes(item.menuName),
+ );
+
+ if (result) {
+ throw new Error('[ERROR] ์๋ฃ๋ง ์ฃผ๋ฌธํ ์ ์์ต๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ // ์ด ์ฃผ๋ฌธ๊ธ์ก
+ totalOrderAmount() {
+ const totalAmount = this.#orderMenu.reduce(
+ (sum, item) => sum + item.price * item.count,
+ 0,
+ );
+
+ return totalAmount;
+ }
+
+ // ๋์ ํธ ๋ฉ๋ด ๊ฐ์
+ dessertCount() {
+ const dessertMenu = this.#orderMenu.filter(
+ (item) => item.type === 'dessert',
+ );
+ const count = dessertMenu.reduce((total, item) => total + item.count, 0);
+
+ return count;
+ }
+
+ // ๋ฉ์ธ ๋ฉ๋ด ๊ฐ์
+ mainCount() {
+ const mainMenu = this.#orderMenu.filter((item) => item.type === 'main');
+ const count = mainMenu.reduce((total, item) => total + item.count, 0);
+
+ return count;
+ }
+}
+
+export default OrderMenu; | JavaScript | ํด๋น ์ฝ๋๋ฅผ ํด๋ก ๋ฐ๊ธฐ ์ด๋ ค์ด ์ํ๋ผ ์ ํํ ํ์ธํ๊ธฐ ์ด๋ ค์ ์กฐ์ฌ์ค๋ฝ๊ฒ ์ฌ์ญค๋ณด๋ค์ ใ
ํน์ ํด๋น ์ ๊ท์์ด "ํฐ๋ณธ์คํ
์ดํฌ-3" ์
๋ ฅ๋ฐ์๋ ํต๊ณผ๋๋์? |
@@ -0,0 +1,126 @@
+import { MENU_PRICE } from '../utils/constants.js';
+
+const MENU_TYPES = Object.freeze({
+ appetizer: ['์์ก์ด์ํ', 'ํํ์ค', '์์ ์๋ฌ๋'],
+ main: ['ํฐ๋ณธ์คํ
์ดํฌ', '๋ฐ๋นํ๋ฆฝ', 'ํด์ฐ๋ฌผํ์คํ', 'ํฌ๋ฆฌ์ค๋ง์คํ์คํ'],
+ dessert: ['์ด์ฝ์ผ์ดํฌ', '์์ด์คํฌ๋ฆผ'],
+ drink: ['์ ๋ก์ฝ๋ผ', '๋ ๋์์ธ', '์ดํ์ธ'],
+});
+
+const LIMIT_NUMBER = Object.freeze({
+ minNumber: 1,
+ maxNumber: 20,
+});
+
+class OrderMenu {
+ #orderMenu;
+
+ constructor(order) {
+ this.#validateFormat(order); // ์
๋ ฅ ํ์ ๊ฒ์ฆ
+ this.#arrayMenu(order); // ๊ฐ๊ฒฉ๊ณผ ํจ๊ป ๋ฐฐ์ด ๊ฐ์ฒด ์ ์ฅ
+ this.#validateMenuItems(); // ๋ฉ๋ด ์ ๋ฌด ๊ฒ์ฆ
+ this.#validateCount(); // ์ฃผ๋ฌธ ๊ฐ์ ๊ฒ์ฆ
+ this.#validateTotalCount(); // ์ฃผ๋ฌธ ์ด๊ฐ์ ๊ฒ์ฆ
+ this.#validateDuplicateMenu(); // ๋ฉ๋ด ์ค๋ณต ๊ฒ์ฆ
+ this.#validateOnlyDrink(); // ์๋ฃ๋ง ์ฃผ๋ฌธ ๊ฒ์ฆ
+ }
+
+ #arrayMenu(order) {
+ const menuItem = order.split(',');
+ this.#orderMenu = menuItem.map((item) => {
+ const [menuName, count] = item.split('-');
+ const price = MENU_PRICE[menuName] || 0;
+ const type = Object.keys(MENU_TYPES).find((category) =>
+ MENU_TYPES[category].includes(menuName),
+ );
+ return { menuName, count: Number(count), price, type };
+ });
+ }
+
+ #validateFormat(order) {
+ const regex = /^([๊ฐ-ํฃ]+-\d+,)*[๊ฐ-ํฃ]+-\d+$/;
+ const testResult = regex.test(order);
+
+ if (testResult === false) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #validateMenuItems() {
+ const result = this.#orderMenu.some((item) => item.price === 0);
+
+ if (result) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #validateCount() {
+ this.#orderMenu.forEach((menu) => {
+ if (menu.count < LIMIT_NUMBER.minNumber) {
+ throw new Error(
+ '[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.',
+ );
+ }
+ });
+ }
+
+ #validateTotalCount() {
+ const totalCount = this.#orderMenu.reduce(
+ (sum, item) => sum + item.count,
+ 0,
+ );
+
+ if (totalCount > LIMIT_NUMBER.maxNumber) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #validateDuplicateMenu() {
+ const menuNameSet = new Set(this.#orderMenu.map((item) => item.menuName));
+
+ if (menuNameSet.size !== this.#orderMenu.length) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #validateOnlyDrink() {
+ const drinkMenu = MENU_TYPES.drink;
+ const result = this.#orderMenu.every((item) =>
+ drinkMenu.includes(item.menuName),
+ );
+
+ if (result) {
+ throw new Error('[ERROR] ์๋ฃ๋ง ์ฃผ๋ฌธํ ์ ์์ต๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ // ์ด ์ฃผ๋ฌธ๊ธ์ก
+ totalOrderAmount() {
+ const totalAmount = this.#orderMenu.reduce(
+ (sum, item) => sum + item.price * item.count,
+ 0,
+ );
+
+ return totalAmount;
+ }
+
+ // ๋์ ํธ ๋ฉ๋ด ๊ฐ์
+ dessertCount() {
+ const dessertMenu = this.#orderMenu.filter(
+ (item) => item.type === 'dessert',
+ );
+ const count = dessertMenu.reduce((total, item) => total + item.count, 0);
+
+ return count;
+ }
+
+ // ๋ฉ์ธ ๋ฉ๋ด ๊ฐ์
+ mainCount() {
+ const mainMenu = this.#orderMenu.filter((item) => item.type === 'main');
+ const count = mainMenu.reduce((total, item) => total + item.count, 0);
+
+ return count;
+ }
+}
+
+export default OrderMenu; | JavaScript | #orderMenu ์์ ๋ฐฐ์ด์ ํํ๋ก ๊ฐ๊ฐ์ ๋ฉ๋ด๊ฐ { menuName, count: Number(count), price, type } ๊ฐ์ฒด ํํ๋ก ๋ด๊ฒจ์ ธ ์ ์ฅ๋๋๊ฒ์ ํ์ธ๋ฉ๋๋ค.
๊ฐ๊ฐ์ ๋ฉ๋ด ๋ํ ํด๋์คํํ๋ก ์ ์ฅํ์ง ์๊ณ ๊ฐ์ฒด ๋ฆฌํฐ๋ด์ ํ์์ผ๋ก ์ ์ฅํ์ ์ด์ ๊ฐ ๊ถ๊ธํ๋ค์ :) |
@@ -0,0 +1,197 @@
+# ๐
๐ป ํฌ๋ฆฌ์ค๋ง์ค ํ๋ก๋ชจ์
๐
+
+## ์งํ ๋ฐฉ์
+
+### ๐ง๐ป ๊ณ ๊ฐ ๐ฉ๐ป
+
+- ๋ฐฉ๋ฌธํ ๋ ์ง๋ฅผ ์
๋ ฅํ๋ค.
+- ์ฃผ๋ฌธํ ๋ฉ๋ด ์ด๋ฆ๊ณผ ์๋์ ์
๋ ฅํ๋ค.
+
+### ๐ช ์๋น ๐ด
+
+1. ์๊ฐ๋ฌธ๊ตฌ๋ฅผ ์ถ๋ ฅํ๋ค.
+2. ๋ฐฉ๋ฌธ ๋ ์ง์ ์ด๋ฒคํธ ํํ ์๋ด๋ฌธ๊ตฌ๋ฅผ ์ถ๋ ฅํ๋ค.
+3. ๊ณ ๊ฐ์ด ์ฃผ๋ฌธํ ๋ฉ๋ด๋ฅผ ์ถ๋ ฅํ๋ค.
+4. ์ฃผ๋ฌธํ ๋ฉ๋ด์ ์ด ๊ธ์ก์ ์ถ๋ ฅํ๋ค.
+5. ์ฆ์ ๋ฉ๋ด์ ์ฌ๋ถ๋ฅผ ์ถ๋ ฅํ๋ค.
+6. ๋ฐ์ ์ ์๋ ๋ชจ๋ ํํ ๋ด์ญ์ ์ถ๋ ฅํ๋ค.
+7. ํํ๋ด์ญ์ ๋ชจ๋ ๋ํ ์ด ๊ธ์ก์ ์ถ๋ ฅํ๋ค.
+8. ์ด ์ฃผ๋ฌธ๊ธ์ก์์ ํ ์ธ๋๋ ๊ธ์ก์ ๋บ ์์ ๊ฒฐ์ ๊ธ์ก์ ์ถ๋ ฅํ๋ค.
+9. ์ด๋ฒคํธ ๋ฐฐ์ง ์ฌ๋ถ๋ฅผ ์ถ๋ ฅํ๋ค.
+
+#### 5๋ฒ, 6๋ฒ, 7๋ฒ, 9๋ฒ์ ๊ฒฝ์ฐ, ์์ผ๋ฉด `์์` ์ ์ถ๋ ฅํ๋ค.
+
+<br>
+
+## ๊ธฐ๋ฅ ๋ชฉ๋ก
+
+### ๐ก ๊ฒ์ฆ ๐
+
+#### ๋ฐฉ๋ฌธ ๋ ์ง
+
+- ์์ฐ์๊ฐ ๋ง๋์ง ํ์ธํ๋ค.
+- 31 ์ดํ์ ์ซ์๊ฐ ๋ง๋์ง ํ์ธํ๋ค.
+
+[x] ๊ฐ ๊ฒ์ฆ ๋ชฉ๋ก์ ํต๊ณผํ์ง ๋ชปํ ๊ฒฝ์ฐ์๋ ์์ธ๊ฐ ๋ฐ์ํ๊ณ ,
+`[ERROR] ์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.` ์๋ฌ ๋ฉ์ธ์ง ์ถ๋ ฅ ํ ์ฌ์
๋ ฅ ๋ฐ๋๋ค.
+
+#### ์ฃผ๋ฌธ ๋ฉ๋ด
+
+- ์ฃผ๋ฌธ ํ์์ด ์์์ ๊ฐ์์ง ํ์ธํ๋ค.
+- ๋ฉ๋ดํ์ ์๋ ๋ฉ๋ด์ธ์ง ํ์ธํ๋ค.
+- ๊ฐ ๋ฉ๋ด์ ์๋์ด 1๊ฐ ์ด์์ธ์ง ํ์ธํ๋ค.
+- ์ฃผ๋ฌธ ๊ฐ์์ ์ดํฉ์ด 20๊ฐ ์ดํ์ธ์ง ํ์ธํ๋ค.
+- ์ค๋ณต๋๋ ๋ฉ๋ด๊ฐ ์๋์ง ํ์ธํ๋ค.
+
+[x] ๊ฐ ๊ฒ์ฆ ๋ชฉ๋ก์ ํต๊ณผํ์ง ๋ชปํ ๊ฒฝ์ฐ์๋ ์์ธ๊ฐ ๋ฐ์ํ๊ณ ,
+`[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.` ์๋ฌ ๋ฉ์ธ์ง ์ถ๋ ฅ ํ ์ฌ์
๋ ฅ ๋ฐ๋๋ค.
+
+- ์๋ฃ๋ง ์ฃผ๋ฌธํ์ง ์์๋์ง ํ์ธํ๋ค.
+
+[x] ์๋ฃ๋ง ์ฃผ๋ฌธํ ๊ฒฝ์ฐ์๋ ์์ธ๊ฐ ๋ฐ์ํ๊ณ ,
+`[ERROR] ์๋ฃ๋ง ์ฃผ๋ฌธํ ์ ์์ต๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.` ์๋ฌ ๋ฉ์ธ์ง ์ถ๋ ฅ ํ ์ฌ์
๋ ฅ ๋ฐ๋๋ค.
+
+---
+
+### ๐ ํํ ๐ธ
+
+- `Benefits` ํด๋์ค ์์ฑํ ๋ `๋ ์ง` ๋ฅผ ๋ฐ๊ณ , **๊ฒ์ฆ ํ ์ํ๊ฐ์ผ๋ก ์ ์ฅ**
+
+- `๋ ์ง` ๋ฅผ ์ด์ฉํด **ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ, ํ์ผ ํ ์ธ, ์ฃผ๋ง ํ ์ธ, ํน๋ณ ํ ์ธ** ์ ๊ณ์ฐํ๋ค.
+
+**๐ 12์ ๋ ์ง ๊ด๋ จ ์ด๋ฒคํธ ์๋ด ๐ข**
+
+| Event Name | Period | Discount Details |
+| ---------------------- | --------------- | ------------------------------------------------------------------- |
+| ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ | 1์ผ ~ 25์ผ | 1์ผ์ `1,000`์์ผ๋ก ์์ํด์ ํ๋ฃจ์ `100`์์ฉ ์ฆ๊ฐํ ๊ฐ์ ํ ์ธํ๋ค. |
+| ํ์ผ ํ ์ธ | ์ผ์์ผ ~ ๋ชฉ์์ผ | ๋์ ํธ ๋ฉ๋ด๋ฅผ 1๊ฐ๋น `2,023`์์ ํ ์ธํ๋ค. |
+| ์ฃผ๋ง ํ ์ธ | ๊ธ์์ผ, ํ ์์ผ | ๋ฉ์ธ ๋ฉ๋ด๋ฅผ 1๊ฐ๋น `2,023`์์ ํ ์ธํ๋ค. |
+| ํน๋ณ ํ ์ธ | ์ผ์์ผ, 25์ผ | `1,000`์์ ํ ์ธํ๋ค. |
+
+---
+
+### ๐ ์ฃผ๋ฌธ ๐งพ
+
+- `OrderMenu` ํด๋์ค ์์ฑํ ๋ `์ฃผ๋ฌธ` ์ ๋ฐ๊ณ , **ํ์ ๊ฒ์ฆ ํ ๊ฐ๊ฒฉ, ํ์
๊ณผ ํจ๊ป ์ํ๊ฐ์ผ๋ก ์ ์ฅํ ๋ค ๋๋จธ์ง ๊ฒ์ฆ ์งํ**
+- ์ฃผ๋ฌธ ๋ด์ญ์ ์ด์ฉํด **๋ฉ์ธ ๋ฉ๋ด์ ๊ฐ์, ๋์ ํธ ๋ฉ๋ด์ ๊ฐ์, ์ด ์ฃผ๋ฌธ๊ธ์ก** ์ ๊ณ์ฐํ๋ค.
+
+**๐ 12์ ์ด ์ฃผ๋ฌธ๊ธ์ก ๊ด๋ จ ์ด๋ฒคํธ ์๋ด ๐ข**
+
+| Event Name | Condition | Gift Description |
+| ----------- | ---------------- | ---------------- |
+| ์ฆ์ ์ด๋ฒคํธ | 12๋ง์ ์ด์ ์ฃผ๋ฌธ | ์ดํ์ธ 1๊ฐ ์ฆ์ |
+
+---
+
+### ๐ ์๋น์ค(ํํ๊ณผ ์ฃผ๋ฌธ์ ์ฐ๊ฒฐ๊ณ ๋ฆฌ) โญ
+
+- ํํ๋ค์ ์ด ํ ์ธ ๊ธ์ก๊ณผ ์ฃผ๋ฌธ์ ์ฆ์ ์ด๋ฒคํธ ์ฌ๋ถ์ ๋ฐ๋ฅธ ํํ ๊ธ์ก์ ๋ํด **์ด ํํ๊ธ์ก** ์ ๊ณ์ฐํ๋ค.
+- ์ด ํํ ๊ธ์ก์ ์ด์ฉํด **๋ฐฐ์ง** ์ ์ฌ๋ถ๋ฅผ ๊ณ์ฐํ๋ค.
+
+**๐ 12์ ์ด๋ฒคํธ ๋ฐฐ์ง ๊ด๋ จ ์๋ด ๐ข**
+
+| Total Benefits | Badge |
+| -------------- | ----- |
+| 5,000์ ์ด์ | ๋ณ |
+| 10,000์ ์ด์ | ํธ๋ฆฌ |
+| 20,000์ ์ด์ | ์ฐํ |
+
+---
+
+### ๐จ ์ฃผ์์ฌํญ ๐ง
+
+#### ํํ ๋ด์ญ
+
+- ๊ณ ๊ฐ์๊ฒ ํด๋น๋ ์ด๋ฒคํธ ๋ด์ญ๋ง ์ถ๋ ฅํ๋ค.
+- ์ด ์ฃผ๋ฌธ๊ธ์ก์ด `10,000`์ ๋ฏธ๋ง์ผ ๊ฒฝ์ฐ, ํํ์ด ์ ์ฉ๋์ง ์์ผ๋ฏ๋ก `์์` ์ ์ถ๋ ฅํ๋ค.
+- ์ ์ฉ๋ ํํ์ด ํ๋๋ ์์ ๊ฒฝ์ฐ, `์์` ์ ์ถ๋ ฅํ๋ค.
+ ```
+ // ์์
+ - 26์ผ~28์ผ์ ๋ฐฉ๋ฌธํ์ฌ ๋์ ํธ ๋ฉ๋ด๋ฅผ ์ํค์ง ์๊ณ , ์ด ์ฃผ๋ฌธ๊ธ์ก์ด 12๋ง์ ๋ฏธ๋ง์ธ ๊ฒฝ์ฐ
+ - 29์ผ, 30์ผ์ ๋ฐฉ๋ฌธํ์ฌ ๋ฉ์ธ ๋ฉ๋ด๋ฅผ ์ํค์ง ์๊ณ , ์ด ์ฃผ๋ฌธ๊ธ์ก์ด 12๋ง์ ๋ฏธ๋ง์ธ ๊ฒฝ์ฐ
+ ```
+
+#### ์ดํํ ๊ธ์ก
+
+- ์ด ์ฃผ๋ฌธ๊ธ์ก์ด `10,000`์ ๋ฏธ๋ง์ผ ๊ฒฝ์ฐ, ํํ์ด ์ ์ฉ๋์ง ์์ผ๋ฏ๋ก `0์` ์ ์ถ๋ ฅํ๋ค.
+
+#### ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก
+
+- ์ฆ์ ์ด๋ฒคํธ๋ ํ ์ธ์ด ์๋๊ธฐ ๋๋ฌธ์ ์ด ์ฃผ๋ฌธ๊ธ์ก์์ ๊ฐ์ ๋นผ์ง ์๋๋ค.
+
+## ํ
์คํธ ์ฝ๋
+
+### ๐ Benefits ํด๋์ค ํ
์คํธ ์ฝ๋ ์์ฑ
+
+- ๋ฐฉ๋ฌธ ๋ ์ง ๊ฒ์ฆ ํ
์คํธ
+
+ - [x] ์ซ์๊ฐ ์๋๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.
+ - [x] ์์ 31 ์ฌ์ด์ ์๊ฐ ์๋๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.
+
+- ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ ํ
์คํธ
+
+ - [x] 1์ผ๋ถํฐ 25์ผ ์ฌ์ด์ ํ ์ธ ๊ธ์ก์ ๊ณ์ฐํ๋ค.
+ - [x] 25์ผ ์ดํ์ ํ ์ธ ๊ธ์ก์ 0์ด๋ค.
+
+- ํ์ผ ํ ์ธ ํ
์คํธ
+
+ - [x] ํ์ผ์ด๋ฉด ๋์ ํธ ๋ฉ๋ด์ ์๋์ ๋ฐ๋ผ ํ ์ธ ๊ธ์ก์ ๊ณ์ฐํ๋ค.
+ - [x] ์ฃผ๋ง์ด๋ฉด ํ ์ธ ๊ธ์ก์ด 0์ด๋ค.
+
+- ์ฃผ๋ง ํ ์ธ ํ
์คํธ
+
+ - [x] ์ฃผ๋ง์ด๋ฉด ๋ฉ์ธ ๋ฉ๋ด์ ์๋์ ๋ฐ๋ผ ํ ์ธ ๊ธ์ก์ ๊ณ์ฐํ๋ค.
+ - [x] ํ์ผ์ด๋ฉด ํ ์ธ ๊ธ์ก์ด 0์ด๋ค.
+
+- ํน๋ณ ํ ์ธ ํ
์คํธ
+ - [x] ์ผ์์ผ์ด๋ 25์ผ์ด๋ฉด ํน๋ณ ํ ์ธ ๊ฐ์ ๋ฐํํ๋ค.
+ - [x] ์ด์ธ์ ๋ ์ ํ ์ธ ๊ธ์ก์ด 0์ด๋ค.
+
+### ๐ OrderMenu ํด๋์ค ํ
์คํธ ์ฝ๋ ์์ฑ
+
+- ์ฃผ๋ฌธ ๋ฉ๋ด ๊ฒ์ฆ ํ
์คํธ
+
+ - [x] ์ฃผ๋ฌธ ํ์์ด ์์์ ๋ค๋ฅด๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.
+ - [x] ๋ฉ๋ดํ์ ์๋ ๋ฉ๋ด๊ฐ ์์ผ๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.
+ - [x] ์ฃผ๋ฌธ ์๋์ด 1 ๋ฏธ๋ง์ด๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.
+ - [x] ์ฃผ๋ฌธ ์๋์ ์ดํฉ์ด 20์ด ๋์ผ๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.
+ - [x] ์ค๋ณต๋ ๋ฉ๋ด๊ฐ ์์ผ๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.
+ - [x] ์๋ฃ๋ง ์ฃผ๋ฌธํ๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ค.
+
+- ์ํ๊ฐ ํ์ฉ ํ
์คํธ
+ - [x] ์๋๊ณผ ๊ฐ๊ฒฉ์ ๊ณฑํด์ ์ด ์ฃผ๋ฌธ๊ธ์ก์ ๊ณ์ฐํ๋ค.
+ - [x] ๋์ ํธ ๋ฉ๋ด์ ์ฃผ๋ฌธ ๊ฐ์๋ฅผ ๊ณ์ฐํ๋ค.
+ - [x] ๋ฉ์ธ ๋ฉ๋ด์ ์ฃผ๋ฌธ ๊ฐ์๋ฅผ ๊ณ์ฐํ๋ค.
+
+### ๐ Service ํด๋์ค ํ
์คํธ ์ฝ๋ ์์ฑ
+
+- ์ด ์ฃผ๋ฌธ๊ธ์ก์ด 12๋ง์ ์ด์์ผ ๋, ์ด ํํ๊ธ์ก ๊ตฌํ๋ ํ
์คํธ
+
+ - [x] ํฌ๋ฆฌ์ค๋ง์ค+ํ์ผ+ํน๋ณ+์ฆ์
+ - [x] ํฌ๋ฆฌ์ค๋ง์ค+ํ์ผ+์ฆ์
+ - [x] ํฌ๋ฆฌ์ค๋ง์ค+์ฃผ๋ง+์ฆ์
+ - [x] ํ์ผ+ํน๋ณ+์ฆ์
+ - [x] ์ฃผ๋ง+์ฆ์
+ - [x] ํฌ๋ฆฌ์ค๋ง์ค+ํน๋ณ+์ฆ์
+ - [x] ํน๋ณ+์ฆ์
+
+- ์ด ์ฃผ๋ฌธ๊ธ์ก์ด 12๋ง์ ๋ฏธ๋ง์ผ ๋, ์ด ํํ๊ธ์ก ๊ตฌํ๋ ํ
์คํธ
+
+ - [x] ํฌ๋ฆฌ์ค๋ง์ค+ํ์ผ+ํน๋ณ
+ - [x] ํฌ๋ฆฌ์ค๋ง์ค+ํ์ผ
+ - [x] ํฌ๋ฆฌ์ค๋ง์ค+์ฃผ๋ง
+ - [x] ํ์ผ+ํน๋ณ
+ - [x] ์ฃผ๋ง
+ - [x] ํฌ๋ฆฌ์ค๋ง์ค+ํน๋ณ
+ - [x] ํน๋ณ
+
+- ์์ ๊ฒฐ์ ๊ธ์ก ๊ณ์ฐ ํ
์คํธ
+
+ - [x] ํํ์ด ์์ผ๋ฉด ์ด ์ฃผ๋ฌธ๊ธ์ก์ ๋ฐํํ๋ค.
+ - [x] ์ฆ์ ์ด๋ฒคํธ๊ฐ ์์ผ๋ฉด ์ด ๊ธ์ก์์ ํํ ๊ธ์ก์ ๋บ๋ค.
+ - [x] ์ฆ์ ์ด๋ฒคํธ๊ฐ ์์ผ๋ฉด ์ดํ์ธ ๊ฐ์ ๋นผ๊ณ ๊ณ์ฐํ๋ค.
+
+- 12์ ์ด๋ฒคํธ ๋ฐฐ์ง ํ
์คํธ
+ - [x] ์ด ํํ๊ธ์ก์ด 5,000์ ์ด์์ด๋ฉด "๋ณ" ๋ฐฐ์ง๋ฅผ ๋ฐํํ๋ค.
+ - [x] ์ด ํํ๊ธ์ก์ด 10,000์ ์ด์์ด๋ฉด "ํธ๋ฆฌ" ๋ฐฐ์ง๋ฅผ ๋ฐํํ๋ค.
+ - [x] ์ด ํํ๊ธ์ก์ด 20,000์ ์ด์์ด๋ฉด "์ฐํ" ๋ฐฐ์ง๋ฅผ ๋ฐํํ๋ค. | Unknown | ์ ์ฑ๋ค์ฌ ์์ฑํ์ ๊ฒ ๋๊ปด์ง๋ README๋ค์ ๐ |
@@ -0,0 +1,88 @@
+const DATE = Object.freeze({
+ eventEndDay: 31,
+ christmasEndDay: 25,
+});
+
+const WEEKDAY = Object.freeze([
+ 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 17, 18, 19, 20, 21, 24, 25, 26, 27, 28, 31,
+]);
+
+const WEEKEND = Object.freeze([1, 2, 8, 9, 15, 16, 22, 23, 29, 30]);
+
+const SPECIAL = Object.freeze([3, 10, 17, 24, 25, 31]);
+
+class Benefits {
+ #date;
+
+ constructor(date) {
+ this.#validateNumber(date); // ์์ฐ์ ๊ฒ์ฆ
+ this.#date = Number(date);
+ this.#validateDate(); // ๋ ์ง ๋ฒ์ ๊ฒ์ฆ
+ }
+
+ #validateNumber(date) {
+ const regex = /^[1-9]\d*$/;
+ const testResult = regex.test(date);
+
+ if (testResult === false) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #validateDate() {
+ if (this.#date > DATE.eventEndDay) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ // ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ
+ christmasDiscount() {
+ const START_PRICE = 1000;
+ const INCREASE_PRICE = 100;
+ let discountedAmount = 0;
+
+ if (this.#date <= DATE.christmasEndDay) {
+ discountedAmount = START_PRICE + (this.#date - 1) * INCREASE_PRICE;
+ }
+
+ return ['ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ', discountedAmount];
+ }
+
+ // ํ์ผ ํ ์ธ
+ weekdayDiscount(dessertCount) {
+ const WEEKDAY_DISCOUNT = 2023;
+ let discountedAmount = 0;
+
+ if (WEEKDAY.includes(this.#date)) {
+ discountedAmount = WEEKDAY_DISCOUNT * dessertCount;
+ }
+
+ return ['ํ์ผ ํ ์ธ', discountedAmount];
+ }
+
+ // ์ฃผ๋ง ํ ์ธ
+ weekendDiscount(mainCount) {
+ const WEEKEND_DISCOUNT = 2023;
+ let discountedAmount = 0;
+
+ if (WEEKEND.includes(this.#date)) {
+ discountedAmount = WEEKEND_DISCOUNT * mainCount;
+ }
+
+ return ['์ฃผ๋ง ํ ์ธ', discountedAmount];
+ }
+
+ // ํน๋ณ ํ ์ธ
+ specialDiscount() {
+ const DISCOUNT_PRICE = 1000;
+ let discountedAmount = 0;
+
+ if (SPECIAL.includes(this.#date)) {
+ discountedAmount = DISCOUNT_PRICE;
+ }
+
+ return ['ํน๋ณ ํ ์ธ', discountedAmount];
+ }
+}
+
+export default Benefits; | JavaScript | ์ฌ์ํ๋ค๋ฉด ์ฌ์ํ ๋ถ๋ถ์ด์ง๋ง '[ERROR] '๋ ๋ชจ๋ ์์ธ ๋ฉ์์ง์์ ์ฌ์ฉ๋๋ฏ๋ก prefix๋ก ์์ํํ์๋ฉด ์ข์ ๊ฒ ๊ฐ์์. ๋ค์ ์ด์ด์ง๋ ์์ธ ๋ฉ์์ง๋ ๋ง์ฐฌ๊ฐ์ง๊ตฌ์! |
@@ -0,0 +1,126 @@
+import { MENU_PRICE } from '../utils/constants.js';
+
+const MENU_TYPES = Object.freeze({
+ appetizer: ['์์ก์ด์ํ', 'ํํ์ค', '์์ ์๋ฌ๋'],
+ main: ['ํฐ๋ณธ์คํ
์ดํฌ', '๋ฐ๋นํ๋ฆฝ', 'ํด์ฐ๋ฌผํ์คํ', 'ํฌ๋ฆฌ์ค๋ง์คํ์คํ'],
+ dessert: ['์ด์ฝ์ผ์ดํฌ', '์์ด์คํฌ๋ฆผ'],
+ drink: ['์ ๋ก์ฝ๋ผ', '๋ ๋์์ธ', '์ดํ์ธ'],
+});
+
+const LIMIT_NUMBER = Object.freeze({
+ minNumber: 1,
+ maxNumber: 20,
+});
+
+class OrderMenu {
+ #orderMenu;
+
+ constructor(order) {
+ this.#validateFormat(order); // ์
๋ ฅ ํ์ ๊ฒ์ฆ
+ this.#arrayMenu(order); // ๊ฐ๊ฒฉ๊ณผ ํจ๊ป ๋ฐฐ์ด ๊ฐ์ฒด ์ ์ฅ
+ this.#validateMenuItems(); // ๋ฉ๋ด ์ ๋ฌด ๊ฒ์ฆ
+ this.#validateCount(); // ์ฃผ๋ฌธ ๊ฐ์ ๊ฒ์ฆ
+ this.#validateTotalCount(); // ์ฃผ๋ฌธ ์ด๊ฐ์ ๊ฒ์ฆ
+ this.#validateDuplicateMenu(); // ๋ฉ๋ด ์ค๋ณต ๊ฒ์ฆ
+ this.#validateOnlyDrink(); // ์๋ฃ๋ง ์ฃผ๋ฌธ ๊ฒ์ฆ
+ }
+
+ #arrayMenu(order) {
+ const menuItem = order.split(',');
+ this.#orderMenu = menuItem.map((item) => {
+ const [menuName, count] = item.split('-');
+ const price = MENU_PRICE[menuName] || 0;
+ const type = Object.keys(MENU_TYPES).find((category) =>
+ MENU_TYPES[category].includes(menuName),
+ );
+ return { menuName, count: Number(count), price, type };
+ });
+ }
+
+ #validateFormat(order) {
+ const regex = /^([๊ฐ-ํฃ]+-\d+,)*[๊ฐ-ํฃ]+-\d+$/;
+ const testResult = regex.test(order);
+
+ if (testResult === false) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #validateMenuItems() {
+ const result = this.#orderMenu.some((item) => item.price === 0);
+
+ if (result) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #validateCount() {
+ this.#orderMenu.forEach((menu) => {
+ if (menu.count < LIMIT_NUMBER.minNumber) {
+ throw new Error(
+ '[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.',
+ );
+ }
+ });
+ }
+
+ #validateTotalCount() {
+ const totalCount = this.#orderMenu.reduce(
+ (sum, item) => sum + item.count,
+ 0,
+ );
+
+ if (totalCount > LIMIT_NUMBER.maxNumber) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #validateDuplicateMenu() {
+ const menuNameSet = new Set(this.#orderMenu.map((item) => item.menuName));
+
+ if (menuNameSet.size !== this.#orderMenu.length) {
+ throw new Error('[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ #validateOnlyDrink() {
+ const drinkMenu = MENU_TYPES.drink;
+ const result = this.#orderMenu.every((item) =>
+ drinkMenu.includes(item.menuName),
+ );
+
+ if (result) {
+ throw new Error('[ERROR] ์๋ฃ๋ง ์ฃผ๋ฌธํ ์ ์์ต๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.');
+ }
+ }
+
+ // ์ด ์ฃผ๋ฌธ๊ธ์ก
+ totalOrderAmount() {
+ const totalAmount = this.#orderMenu.reduce(
+ (sum, item) => sum + item.price * item.count,
+ 0,
+ );
+
+ return totalAmount;
+ }
+
+ // ๋์ ํธ ๋ฉ๋ด ๊ฐ์
+ dessertCount() {
+ const dessertMenu = this.#orderMenu.filter(
+ (item) => item.type === 'dessert',
+ );
+ const count = dessertMenu.reduce((total, item) => total + item.count, 0);
+
+ return count;
+ }
+
+ // ๋ฉ์ธ ๋ฉ๋ด ๊ฐ์
+ mainCount() {
+ const mainMenu = this.#orderMenu.filter((item) => item.type === 'main');
+ const count = mainMenu.reduce((total, item) => total + item.count, 0);
+
+ return count;
+ }
+}
+
+export default OrderMenu; | JavaScript | https://regexr.com/
์ด ์ฌ์ดํธ ์ ์ฉํฉ๋๋ค! |
@@ -0,0 +1,141 @@
+## ๐ ๊ตฌํ ๋์
+
+### ํฌ๋ฆฌ์ค๋ง์ค ํ๋ก๋ชจ์
+
+### - ๋ชฉํ
+
+=> ์ ์ฐ์ฑ๊ณผ ํ์ฅ์ฑ์ ๊ฐ์กฐํ 12์ ์ด๋ฒคํธ ํ๋๋๋ฅผ ๊ฐ๋ฐํ์ฌ ๋ณํ์ ๋์ํ๊ณ , ๊ฐ์ฒด์งํฅ์ ์ฅ์ ์ ์ต๋ํ ํ์ฉํ๋ค.
+์ค์์ฒ๋ฆฌ์ ์์คํ
์ด ์๋ ๊ฐ์ฒด ๊ฐ์ ํ๋ ฅ์ ๊ฐ์กฐํ์ฌ '์ด์์๋' ์์คํ
์ ์ค๊ณํ๊ณ ,
+๋ชจ๋ ๋๋ฉ์ธ ๋ก์ง์ ์ฒ ์ ํ ๋จ์ ํ
์คํธ๋ฅผ ๋์
ํ์ฌ ์์คํ
์ ๋ฌด๊ฒฐ์ฑ์ ๋ณด์ฅํ๋ค.
+์ด๋ฅผ ํตํด ํ์ฅ์ฑ ์๊ณ ์ ์ง๋ณด์๊ฐ ์ฉ์ดํ ํจ๊ณผ์ ์ธ ์ด๋ฒคํธ ํ๋๋๋ฅผ ๊ตฌ์ถํ๋ค.
+
+### - ์ธ๋ถ ๋ชฉํ ๋ฐ ์ง์นจ
+
+- ํด๋์ค๋ณด๋ค๋ ๋ฉ์์ง ์ค์ฌ ์ค๊ณ
+- UI๋ ๋๋ฉ์ธ ๋ก์ง๊ณผ ๋ถ๋ฆฌ
+- ๋จ์ผ ์ฑ
์ ์์น์ ์งํค์
+- ์์กด์ฑ ์ญ์ ์์น์ ์งํค์
+- ํด๋์ค ๋ถ๋ฆฌ ๋ฐ ์ญํ ๋ถ์ฌ
+- ์ญํ , ์ฑ
์, ํ๋ ฅ ์ค๊ณ
+- ์ธ์คํด์ค ๋ณ์์ ์๋ฅผ ์ค์ด๊ธฐ ์ํด ๋
ธ๋ ฅํ์
+- ๋ฌด๋ถ๋ณํ getter ์ฌ์ฉ ๋์ ๊ฐ์ฒด์ ๋ฉ์์ง๋ฅผ ๋ณด๋ด ๊ฐ์ฒด๊ฐ ๋ก์ง์ ์ํํ๋๋ก ํ์
+- ๊ฐ์ฒด๋ ๊ฐ์ฒด์ค๋ฝ๊ฒ ์ฌ์ฉํ์
+- ๋จ์ ํ
์คํธํ๊ธฐ ์ด๋ ค์ด ์ฝ๋๋ฅผ ๋จ์ ํ
์คํธํด๋ณด์
+
+---
+
+### - ์ค๊ณ
+
+#### 1์ฐจ ๋จ๊ณ (๋ฉ์ธ์ง ๋ค์ด์ด๊ทธ๋จ ๊ตฌ์ฑ)
+
+<img src="image/xmas_promo_3rd_msg.png">
+
+#### ๊ธฐ๋ฅ ๋ช
์ธ
+
+- ์
๋ ฅ
+
+> [๊ธฐ๋ฅ] ๋ฐฉ๋ฌธ ๋ ์ง๋ฅผ ์
๋ ฅ๋ฐ๋ ๊ธฐ๋ฅ<br>
+> [๊ธฐ๋ฅ] ์ฃผ๋ฌธํ ๋ฉ๋ด์ ๊ฐฏ์๋ฅผ ์
๋ ฅ๋ฐ๋ ๊ธฐ๋ฅ<br>
+
+- ์ถ๋ ฅ
+
+> [๊ธฐ๋ฅ] ๊ณ ๊ฐ์๊ฒ ์๋ดํ ์ด๋ฒคํธ ์ฃผ์์ฌํญ์ ์ถ๋ ฅํ๋ ๊ธฐ๋ฅ
+> - ์ด์ฃผ๋ฌธ ๊ธ์ก 10,000์ ์ด์๋ถํฐ ์ด๋ฒคํธ๊ฐ ์ ์ฉ๋๋ค๊ณ ์ถ๋ ฅํ๋ ๊ธฐ๋ฅ<br>
+> - ์๋ฃ๋ง ์ฃผ๋ฌธ ์, ์ฃผ๋ฌธํ ์ ์๋ค๊ณ ์ถ๋ ฅํ๋ ๊ธฐ๋ฅ<br>
+> - ๋ฉ๋ด๋ ํ ๋ฒ์ ์ต๋ 20๊ฐ๊น์ง๋ง ์ฃผ๋ฌธํ ์ ์๋ค๊ณ ์ถ๋ ฅํ๋ ๊ธฐ๋ฅ<br>
+
+> [๊ธฐ๋ฅ] ์ด๋ฒคํธ ํ๋๋ ์คํ ๊ฒฐ๊ณผ ์ถ๋ ฅํ๋ ๊ธฐ๋ฅ
+> - ์ฃผ๋ฌธ ๋ฉ๋ด๋ฅผ ์ถ๋ ฅํ๋ ๊ธฐ๋ฅ<br>
+> - ํ ์ธ ์ ์ด ์ฃผ๋ฌธ ๊ธ์ก ์ถ๋ ฅํ๋ ๊ธฐ๋ฅ<br>
+> - ์ฆ์ ๋ฉ๋ด๋ฅผ ์ถ๋ ฅํ๋ ๊ธฐ๋ฅ<br>
+> - ํํ ๋ด์ญ ์ถ๋ ฅํ๋ ๊ธฐ๋ฅ<br>
+> - ์ดํํ ๊ธ์ก์ ์ถ๋ ฅํ๋ ๊ธฐ๋ฅ<br>
+> - ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก์ ์ถ๋ ฅํ๋ ๊ธฐ๋ฅ<br>
+> - 12์ ์ด๋ฒคํธ ๋ฐฐ์ง๋ฅผ ์ถ๋ ฅํ๋ ๊ธฐ๋ฅ<br>
+
+> [๊ธฐ๋ฅ] ์๋ฌ ๋ฉ์์ง ์ถ๋ ฅํ๋ ๊ธฐ๋ฅ
+> - ์์ธ ๋ช
์ธ์์ ๋ช
์๋ ์์ธ์ ๋ํ ๋ฉ์์ง๋ฅผ ์ถ๋ ฅํ๋ ๊ธฐ๋ฅ
+
+- ๋ก์ง
+
+> [๊ธฐ๋ฅ] ๋ฉ๋ด ๊ด๋ จ ๊ธฐ๋ฅ <br>
+> - ๋ฉ๋ด ๋ชฉ๋ก์ ๋ง๋๋ ๊ธฐ๋ฅ<br>
+> - ๋ฉ๋ด์ ์ด๋ฆ์ ๋ฐํํ๋ ๊ธฐ๋ฅ <br>
+> - ๋ฉ๋ด์ ๊ฐ๊ฒฉ์ ๋ฐํํ๋ ๊ธฐ๋ฅ <br>
+> - ๋ฉ๋ด์ ํ์
(์ํผํ์ด์ /๋ฉ์ธ/๋์ ํธ/์๋ฃ)์ ๋ฐํํ๋ ๊ธฐ๋ฅ<br>
+> - ๋ฉ๋ด ์ด๋ฆ์ ๊ธฐ๋ฐ์ผ๋ก ๋ฉ๋ด ๊ฐ์ฒด๋ฅผ ๊ฐ์ ธ์ค๋ ๊ธฐ๋ฅ<br>
+
+> [๊ธฐ๋ฅ] ์ฆ์ ๋ฉ๋ด ๊ด๋ จ ๊ธฐ๋ฅ <br>
+> - ์ฆ์ ๋ฉ๋ด ๋ชฉ๋ก์ ๋ง๋๋ ๊ธฐ๋ฅ<br>
+> - ์ฆ์ ๋ฉ๋ด์ ์ด๋ฆ์ ๋ฐํํ๋ ๊ธฐ๋ฅ<br>
+> - ์ฆ์ ๋ฉ๋ด์ ์ด๊ฐ๊ฒฉ(๊ฐ๊ฒฉ * ์๋)์ ๋ฐํํ๋ ๊ธฐ๋ฅ<br>
+> - ์ฆ์ ๋ฉ๋ด ๋ชฉ๋ก์ ์ด ๊ฐ๊ฒฉ์ ๋ฐํํ๋ ๊ธฐ๋ฅ<br>
+> - ์ถ๋ ฅํ ์ฆ์ ๋ฉ๋ด ์ ๋ณด๋ฅผ ๋ง๋๋ ๊ธฐ๋ฅ<br>
+
+> [๊ธฐ๋ฅ] ์ฃผ๋ฌธ ๊ด๋ จ ๊ธฐ๋ฅ <br>
+> - ์ฃผ๋ฌธ ํญ๋ชฉ ํ๋์ ์ด๊ฐ๊ฒฉ(๊ฐ๊ฒฉ * ์๋)์ ๊ณ์ฐํ๋ ๊ธฐ๋ฅ<br>
+> - ์ฃผ๋ฌธ ํญ๋ชฉ์ ์ด๋ฆ์ ๋ฐํํ๋ ๊ธฐ๋ฅ<br>
+> - ์ฃผ๋ฌธ ํญ๋ชฉ์ ์๋์ ๋ฐํํ๋ ๊ธฐ๋ฅ<br>
+> - ์ฃผ๋ฌธ ํญ๋ชฉ์ ๋ฉ๋ด ํ์
์ ๋ฐํํ๋ ๊ธฐ๋ฅ<br>
+> - ์ฃผ๋ฌธ์ ์ฃผ๋ฌธ ํญ๋ชฉ์ ์ถ๊ฐํ๋ ๊ธฐ๋ฅ <br>
+> - ์ฃผ๋ฌธ ํญ๋ชฉ๋ค์ ๋ฐํํ๋ ๊ธฐ๋ฅ <br>
+> - ์ด ์ฃผ๋ฌธ ๊ธ์ก(ํ ์ธ ์ ์ด ์ฃผ๋ฌธ ๊ธ์ก)์ ๊ณ์ฐํ๋ ๊ธฐ๋ฅ<br>
+> - ์ถ๋ ฅํ ์ฃผ๋ฌธ ์ ๋ณด๋ฅผ ๋ง๋๋ ๊ธฐ๋ฅ<br>
+
+> [๊ธฐ๋ฅ] ๋ ์ง ๊ด๋ จ ๊ธฐ๋ฅ <br>
+> - ๋ ์ง๋ฅผ ๋ฐํํ๋ ๊ธฐ๋ฅ<br>
+> - ๋ ์ง๊ฐ ๊ธ์์ผ์ธ์ง ์ฒดํฌํ๋ ๊ธฐ๋ฅ<br>
+> - ๋ ์ง๊ฐ ํ ์์ผ์ธ์ง ์ฒดํฌํ๋ ๊ธฐ๋ฅ<br>
+> - ๋ ์ง๊ฐ ์ผ์์ผ์ธ์ง ์ฒดํฌํ๋ ๊ธฐ๋ฅ<br>
+> - ๋ ์ง๊ฐ ํฌ๋ฆฌ์ค๋ง์ค์ธ์ง ์ฒดํฌํ๋ ๊ธฐ๋ฅ<br>
+> - ๋ ์ง๊ฐ ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ๊ธฐ๊ฐ์ธ์ง ์ฒดํฌํ๋ ๊ธฐ๋ฅ<br>
+> - ๋ ์ง๊ฐ ํ์ผ์ธ์ง ์ฒดํฌํ๋ ๊ธฐ๋ฅ<br>
+> - ๋ ์ง๊ฐ ์ฃผ๋ง์ธ์ง ์ฒดํฌํ๋ ๊ธฐ๋ฅ<br>
+> - ๋ ์ง๊ฐ ๋ณ์ ๊ฐ์ง๋์ง ์ฒดํฌํ๋ ๊ธฐ๋ฅ<br>
+
+> [๊ธฐ๋ฅ] ์ด๋ฒคํธ ํ ์ธ๊ณผ ๊ด๋ จ๋ ๊ธฐ๋ฅ <br>
+> - ๋ฐฉ๋ฌธ ๋ ์ง์ ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ ๊ธ์ก์ ๊ณ์ฐํ๋ ๊ธฐ๋ฅ<br>
+> - ๋ฐฉ๋ฌธ ๋ ์ง์ ํ์ผ ํ ์ธ ๊ธ์ก์ ๊ณ์ฐํ๋ ๊ธฐ๋ฅ<br>
+> - ๋ฐฉ๋ฌธ ๋ ์ง์ ์ฃผ๋ง ํ ์ธ ๊ธ์ก์ ๊ณ์ฐํ๋ ๊ธฐ๋ฅ<br>
+> - ๋ฐฉ๋ฌธ ๋ ์ง์ ํน๋ณ ํ ์ธ ๊ธ์ก์ ๊ณ์ฐํ๋ ๊ธฐ๋ฅ<br>
+
+> [๊ธฐ๋ฅ] ์ฆ์ ์ด๋ฒคํธ์ ๊ด๋ จ๋ ๊ธฐ๋ฅ <br>
+> - ์ฆ์ ์ด๋ฒคํธ๋ฅผ ์ ์ฉ ๊ฐ๋ฅํ์ง ์ฒดํฌํ๋ ๊ธฐ๋ฅ<br>
+> - ์ฆ์ ์ด๋ฒคํธ๋ก ํํ๋ณธ ๊ธ์ก์ ๊ณ์ฐํ๋ ๊ธฐ๋ฅ<br>
+
+> [๊ธฐ๋ฅ] ํํ ๋ด์ญ๊ณผ ๊ด๋ จ๋ ๊ธฐ๋ฅ <br>
+> - ์ฃผ๋ฌธ์ ์ด๋ฒคํธ๋ฅผ ์ ์ฉ ๊ฐ๋ฅํ์ง ์ฒดํฌํ๋ ๊ธฐ๋ฅ<br>
+> - ํํ ๋ด์ญ์ ์์ฑํ๋ ๊ธฐ๋ฅ <br>
+> - ์ด ํํ ๊ธ์ก์ ๋ฐํํ๋ ๊ธฐ๋ฅ<br>
+> - ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก์ ๋ฐํํ๋ ๊ธฐ๋ฅ<br>
+> - ์ถ๋ ฅํ ํํ ๋ด์ญ ์ ๋ณด๋ฅผ ๋ง๋๋ ๊ธฐ๋ฅ<br>
+
+> [๊ธฐ๋ฅ] ์ด๋ฒคํธ ๋ฐฐ์ง์ ๊ด๋ จ๋ ๊ธฐ๋ฅ<br>
+> - ์ดํํ ๊ธ์ก์ ๋ฐ๋ผ ์ด๋ฒคํธ ๋ฒ ์ง๋ฅผ ๋ง๋๋ ๊ธฐ๋ฅ<br>
+> - ์ด๋ฒคํธ ๋ฐฐ์ง๋ฅผ ๋ฐํํ๋ ๊ธฐ๋ฅ<br>
+
+> [๊ธฐ๋ฅ] ๊ธฐํ ๊ธฐ๋ฅ <br>
+> - ์
๋ ฅํ ์ฃผ๋ฌธ์ ๋ฐํ์ผ๋ก ์ฃผ๋ฌธ ๊ฐ์ฒด๋ฅผ ๋ง๋๋ ๊ธฐ๋ฅ<br>
+> - ๊ธ์ก์ ###.##0 ํ์์ผ๋ก ํฌ๋งคํ
ํ๋ ๊ธฐ๋ฅ<br>
+
+
+- ์์ธ
+> [์์ธ] ์
๋ ฅ๋ฐ์ ๋ฐฉ๋ฌธ ๋ ์ง ๋ํ ์์ธ์ฒ๋ฆฌ
+> - ๋ฐฉ๋ฌธ ๋ ์ง๊ฐ ์ซ์๊ฐ ์๋ ๊ฒฝ์ฐ<br>
+> - ๋ฐฉ๋ฌธ ๋ ์ง๊ฐ 1~31์ ๋ฒ์ด๋๋ ๊ฒฝ์ฐ<br>
+
+> [์์ธ] ์
๋ ฅ๋ฐ์ ์ฃผ๋ฌธ ๋ฉ๋ด์ ๋ํ ์์ธ์ฒ๋ฆฌ
+> - ๋ฉ๋ด ํ์์ด ์์์ ๋ค๋ฅธ ๊ฒฝ์ฐ<br>
+> - ๋ฉ๋ดํ์ ์๋ ๋ฉ๋ด๋ฅผ ์
๋ ฅํ ๊ฒฝ์ฐ<br>
+> - ์ค๋ณต ๋ฉ๋ด๋ฅผ ์
๋ ฅํ ๊ฒฝ์ฐ<br>
+> - ์
๋ ฅํ ๋ฉ๋ด์ ๊ฐฏ์๊ฐ 1 ์ด์์ ์ซ์๊ฐ ์๋ ๊ฒฝ์ฐ<br>
+
+> [์์ธ] ๋ฐํ์ ์์ธ์ฒ๋ฆฌ
+> - ์ฃผ๋ฌธ๋ด์ญ์ด 20๊ฐ๋ฅผ ์ด๊ณผํ๋ ๊ฒฝ์ฐ<br>
+> - ์๋ฃ๋ง ์ฃผ๋ฌธํ ๊ฒฝ์ฐ<br>
+
+---
+### - ์ต์ข
ํด๋์ค ๋ค์ด์ด๊ทธ๋จ
+<img src="image/xmasFinalDiagram.png">
+
+ | Unknown | ์ด๋ค ๋ถ๋ถ์ ๊ณ ๋ฏผํ๊ณ ๊ตฌํํ์
จ๋์ง ๋ณด๊ธฐ ํธํด์ ์ข๋ค์ ๐๐ |
@@ -0,0 +1,54 @@
+package christmas.controller;
+
+import christmas.domain.entity.Day;
+import christmas.domain.entity.Order;
+import christmas.view.InputView;
+import java.util.function.Supplier;
+
+import static christmas.domain.verifier.RuntimeVerifier.RUNTIME_VERIFIER;
+import static christmas.system.IOMessage.ORDER_PROMPT_MESSAGE;
+import static christmas.system.IOMessage.VISIT_DATE_PROMPT_MESSAGE;
+import static christmas.view.InputView.*;
+import static christmas.view.OutputView.*;
+
+public class PlannerSystem {
+
+ private final Day day;
+ private final Order order;
+ private final SettlementSystem settlementSystem;
+
+ public PlannerSystem() {
+ printMessage(VISIT_DATE_PROMPT_MESSAGE);
+ this.day = readDay();
+ printEventNotice();
+ printMessage(ORDER_PROMPT_MESSAGE);
+ this.order = readOrder(InputView::tryReadOrder);
+ this.settlementSystem = new SettlementSystem(day, order);
+ }
+ public void run() {
+ renderResult();
+ }
+
+ private Order readOrder(Supplier<Order> orderSupplier) {
+ while (true) {
+ try {
+ Order order = orderSupplier.get();
+ RUNTIME_VERIFIER.validate(order);
+ return order;
+ } catch (IllegalStateException e) {
+ printMessage(e.getMessage());
+ }
+ }
+ }
+
+ private void renderResult() {
+ renderPlannerResult();
+ settlementSystem.renderSettlementResult();
+
+ }
+
+ private void renderPlannerResult() {
+ printResultStartMessage(day);
+ printOrderList(order);
+ }
+} | Java | renderResult()๋ฅผ ๋ฐ๋ก ๋ฉ์๋๋ก ๋นผ์ ์ด์ ๊ฐ ์์ผ์ค๊น์? |
@@ -0,0 +1,54 @@
+package christmas.controller;
+
+import christmas.domain.entity.Day;
+import christmas.domain.entity.Order;
+import christmas.view.InputView;
+import java.util.function.Supplier;
+
+import static christmas.domain.verifier.RuntimeVerifier.RUNTIME_VERIFIER;
+import static christmas.system.IOMessage.ORDER_PROMPT_MESSAGE;
+import static christmas.system.IOMessage.VISIT_DATE_PROMPT_MESSAGE;
+import static christmas.view.InputView.*;
+import static christmas.view.OutputView.*;
+
+public class PlannerSystem {
+
+ private final Day day;
+ private final Order order;
+ private final SettlementSystem settlementSystem;
+
+ public PlannerSystem() {
+ printMessage(VISIT_DATE_PROMPT_MESSAGE);
+ this.day = readDay();
+ printEventNotice();
+ printMessage(ORDER_PROMPT_MESSAGE);
+ this.order = readOrder(InputView::tryReadOrder);
+ this.settlementSystem = new SettlementSystem(day, order);
+ }
+ public void run() {
+ renderResult();
+ }
+
+ private Order readOrder(Supplier<Order> orderSupplier) {
+ while (true) {
+ try {
+ Order order = orderSupplier.get();
+ RUNTIME_VERIFIER.validate(order);
+ return order;
+ } catch (IllegalStateException e) {
+ printMessage(e.getMessage());
+ }
+ }
+ }
+
+ private void renderResult() {
+ renderPlannerResult();
+ settlementSystem.renderSettlementResult();
+
+ }
+
+ private void renderPlannerResult() {
+ printResultStartMessage(day);
+ printOrderList(order);
+ }
+} | Java | outputView๋ฅผ static์ผ๋ก ํ์ ์ด์ ๊ฐ ์์ผ์ค๊น์? |
@@ -0,0 +1,54 @@
+package christmas.controller;
+
+import christmas.domain.entity.Day;
+import christmas.domain.entity.Order;
+import christmas.view.InputView;
+import java.util.function.Supplier;
+
+import static christmas.domain.verifier.RuntimeVerifier.RUNTIME_VERIFIER;
+import static christmas.system.IOMessage.ORDER_PROMPT_MESSAGE;
+import static christmas.system.IOMessage.VISIT_DATE_PROMPT_MESSAGE;
+import static christmas.view.InputView.*;
+import static christmas.view.OutputView.*;
+
+public class PlannerSystem {
+
+ private final Day day;
+ private final Order order;
+ private final SettlementSystem settlementSystem;
+
+ public PlannerSystem() {
+ printMessage(VISIT_DATE_PROMPT_MESSAGE);
+ this.day = readDay();
+ printEventNotice();
+ printMessage(ORDER_PROMPT_MESSAGE);
+ this.order = readOrder(InputView::tryReadOrder);
+ this.settlementSystem = new SettlementSystem(day, order);
+ }
+ public void run() {
+ renderResult();
+ }
+
+ private Order readOrder(Supplier<Order> orderSupplier) {
+ while (true) {
+ try {
+ Order order = orderSupplier.get();
+ RUNTIME_VERIFIER.validate(order);
+ return order;
+ } catch (IllegalStateException e) {
+ printMessage(e.getMessage());
+ }
+ }
+ }
+
+ private void renderResult() {
+ renderPlannerResult();
+ settlementSystem.renderSettlementResult();
+
+ }
+
+ private void renderPlannerResult() {
+ printResultStartMessage(day);
+ printOrderList(order);
+ }
+} | Java | static import๋ฅผ ํ์ค ๋๋ ์ด๋ค ๊ฒ๋ค์ importํ๋์ง ์ ๋ํ๋ ์ ์๋๋ก ์์ผ๋์นด๋(*)๋ฅผ ์ฌ์ฉํ์ง์๊ณ ์ ๋ถ ํ์ํ๋ ๊ฒ์ ์ถ์ฒํ๋๋ผ๊ตฌ์.
์ฐธ๊ณ ํ์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,32 @@
+package christmas.controller;
+
+import christmas.domain.entity.Day;
+import christmas.domain.entity.DiscountRecord;
+import christmas.domain.entity.Order;
+import christmas.domain.manager.BonusEventManager;
+import christmas.domain.manager.DiscountManager;
+
+import static christmas.domain.entity.EventBadge.createBadge;
+import static christmas.view.OutputView.*;
+
+public class SettlementSystem {
+
+ private final Order order;
+ private final DiscountRecord discountRecord;
+
+ public SettlementSystem(Day day, Order order) {
+ DiscountManager discountManager = new DiscountManager();
+ BonusEventManager bonusEventManager = new BonusEventManager();
+ this.order = order;
+ this.discountRecord = DiscountRecord.create(day, order, discountManager, bonusEventManager);
+ }
+
+ public void renderSettlementResult() {
+ printOriginalTotalAmount(order);
+ printBonusMenu(order);
+ printDiscountRecord(discountRecord);
+ printTotalDiscountAmount(discountRecord);
+ printExpectedPayment(order, discountRecord);
+ printEventBadge(createBadge(discountRecord));
+ }
+} | Java | ์ ๋ ์ปจํธ๋กค๋ฌ๋ฅผ ์ฌ๋ฌ๊ฐ์ง๋ก ๋๋ ๋ณด๋ ค๊ณ ํ์ด์ ๋ฐ๊ฐ๋ค์!
์ด๋ค ๊ธฐ์ค์ผ๋ก ๋๋ ๋ณด๋ ค๊ณ ํ์
จ๋์ง ๊ถ๊ธํด์ |
@@ -0,0 +1,48 @@
+package christmas.domain.entity;
+
+import christmas.domain.util.Util;
+
+import java.util.Arrays;
+
+import static christmas.system.IOMessage.EMPTY_STRING;
+import static christmas.system.IOMessage.QUANTITY_UNIT;
+
+public enum BonusMenu {
+ CHAMPAGNE(Menu.CHAMPAGNE, 1);
+
+ private final Menu menu;
+ private final int quantity;
+
+ BonusMenu(Menu menu, int quantity) {
+ this.menu = menu;
+ this.quantity = quantity;
+ }
+
+ public static int calculateTotalPriceForAllMenus() {
+ return Arrays.stream(BonusMenu.values())
+ .mapToInt(BonusMenu::getTotalPrice)
+ .sum();
+ }
+
+ public static String generateAllMenuDetails() {
+ StringBuilder stringBuilder = new StringBuilder();
+ for (BonusMenu bonusMenu : BonusMenu.values()) {
+ stringBuilder.append(bonusMenu.toString()).append(System.lineSeparator());
+ }
+ return stringBuilder.toString();
+ }
+
+ @Override
+ public String toString() {
+ return getName() + EMPTY_STRING + Util.createFormattedAmount(quantity) + QUANTITY_UNIT;
+ }
+
+ private String getName() {
+ return menu.getMenuName();
+ }
+
+ private int getTotalPrice() {
+ return menu.getMenuPrice() * quantity;
+ }
+
+} | Java | ์ด๋ถ๋ถ์ ์ถ๋ ฅ ๋ถ๋ถ๊ณผ ๊ด๊ณ ์์ด์ OutputView๊ฐ ์ผํ๊ฒ ํ๋ ๊ฒ์ ์ด๋จ๊น์? |
@@ -0,0 +1,65 @@
+package christmas.domain.manager;
+
+
+import christmas.domain.entity.Day;
+import christmas.domain.entity.Order;
+
+import static christmas.domain.entity.MenuType.*;
+import static christmas.system.Constant.ZERO;
+
+public class DiscountManager {
+
+ private final int DISCOUNT_AMOUNT = 2023;
+ private final int INITIAL_DISCOUNT_AMOUNT = 1000;
+ private final int DAILY_DISCOUNT_INCREASE = 100;
+
+ public DiscountManager() {
+ }
+
+ public int calculateDDayDiscount(Day day) {
+ if (day.isChristmasSeason()) {
+ return calculateDDayAmount(day);
+ }
+ return ZERO;
+ }
+
+ public int calculateWeekDayDiscount(Day day, Order order) {
+ if (day.isWeekday()) {
+ return calculateWeekDayAmount(order);
+ }
+ return ZERO;
+ }
+
+ public int calculateWeekendDiscount(Day day, Order order) {
+ if (day.isWeekend()) {
+ return calculateWeekendAmount(order);
+ }
+ return ZERO;
+ }
+
+ public int calculateSpecialDayDiscount(Day day) {
+ int STAR_DISCOUNT = 1000;
+ if (day.isSpecialDay()) {
+ return STAR_DISCOUNT;
+ }
+ return ZERO;
+ }
+
+ private int calculateDDayAmount(Day day) {
+ return INITIAL_DISCOUNT_AMOUNT + DAILY_DISCOUNT_INCREASE * (day.getDay() - 1);
+ }
+
+ private int calculateWeekDayAmount(Order order) {
+ return order.getOrderItems().stream()
+ .filter(orderItem -> orderItem.getMenuType() == DESSERT)
+ .mapToInt(orderItem -> DISCOUNT_AMOUNT * orderItem.getQuantity())
+ .sum();
+ }
+
+ private int calculateWeekendAmount(Order order) {
+ return order.getOrderItems().stream()
+ .filter(orderItem -> orderItem.getMenuType() == MAIN)
+ .mapToInt(orderItem -> DISCOUNT_AMOUNT * orderItem.getQuantity())
+ .sum();
+ }
+} | Java | day ๊ฐ์ฒด์ ํด๋น ๋ฉ์๋๋ฅผ ๋ฃ์ด๋์ผ๋ ์ฝ๊ธฐ๋ ๋งค์ฐ ํธํด์ ์ข๋ค์ ๐๐ |
@@ -0,0 +1,12 @@
+package christmas.domain.util;
+
+
+import java.text.DecimalFormat;
+
+public final class Util {
+ public static String createFormattedAmount(int target) {
+ DecimalFormat formatter = new DecimalFormat("###,##0");
+ return formatter.format(target);
+ }
+
+} | Java | split ํ๋ ๊ธฐ์ค์ด ๋์ค์๋ ๋ฌ๋ผ์ง ์ ์์ผ๋ ์์๋ก ๋ง๋ค์ด ๊ด๋ฆฌํ๋ฉด ๋์ค์ ์ ์ง๋ณด์ํ๊ธฐ ์ข์ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,54 @@
+package christmas.controller;
+
+import christmas.domain.entity.Day;
+import christmas.domain.entity.Order;
+import christmas.view.InputView;
+import java.util.function.Supplier;
+
+import static christmas.domain.verifier.RuntimeVerifier.RUNTIME_VERIFIER;
+import static christmas.system.IOMessage.ORDER_PROMPT_MESSAGE;
+import static christmas.system.IOMessage.VISIT_DATE_PROMPT_MESSAGE;
+import static christmas.view.InputView.*;
+import static christmas.view.OutputView.*;
+
+public class PlannerSystem {
+
+ private final Day day;
+ private final Order order;
+ private final SettlementSystem settlementSystem;
+
+ public PlannerSystem() {
+ printMessage(VISIT_DATE_PROMPT_MESSAGE);
+ this.day = readDay();
+ printEventNotice();
+ printMessage(ORDER_PROMPT_MESSAGE);
+ this.order = readOrder(InputView::tryReadOrder);
+ this.settlementSystem = new SettlementSystem(day, order);
+ }
+ public void run() {
+ renderResult();
+ }
+
+ private Order readOrder(Supplier<Order> orderSupplier) {
+ while (true) {
+ try {
+ Order order = orderSupplier.get();
+ RUNTIME_VERIFIER.validate(order);
+ return order;
+ } catch (IllegalStateException e) {
+ printMessage(e.getMessage());
+ }
+ }
+ }
+
+ private void renderResult() {
+ renderPlannerResult();
+ settlementSystem.renderSettlementResult();
+
+ }
+
+ private void renderPlannerResult() {
+ printResultStartMessage(day);
+ printOrderList(order);
+ }
+} | Java | ์ฌ์ค ์ด๊ฒ system. run()์ ์ฌ๋ฌ ๊ธฐ๋ฅ์ค์ ํ๋๊ฐ renderResult()์ด๋ผ๊ณ ์๊ฐํด์ ๋บ์ด์!. ๋์ค์ ํ์ฅ์ฑ์๊ฒ ๋ค๋ฅธ ๊ธฐ๋ฅ๋ค๋ ๋ฃ์์ ์๊ฒํ๊ธฐ ์ํด์์! |
@@ -0,0 +1,27 @@
+package christmas.system;
+
+public final class IOMessage {
+ public static final String VISIT_DATE_PROMPT_MESSAGE = "์๋
ํ์ธ์! ์ฐํ
์ฝ ์๋น 12์ ์ด๋ฒคํธ ํ๋๋์
๋๋ค.\n" +
+ "12์ ์ค ์๋น ์์ ๋ฐฉ๋ฌธ ๋ ์ง๋ ์ธ์ ์ธ๊ฐ์? (์ซ์๋ง ์
๋ ฅํด ์ฃผ์ธ์!)";
+
+ public static final String ORDER_PROMPT_MESSAGE = "์ฃผ๋ฌธํ์ค ๋ฉ๋ด๋ฅผ ๋ฉ๋ด์ ๊ฐ์๋ฅผ ์๋ ค ์ฃผ์ธ์. (e.g. ํด์ฐ๋ฌผํ์คํ-2,๋ ๋์์ธ-1,์ด์ฝ์ผ์ดํฌ-1)";
+
+ public static final String NONE = "์์";
+ public static final String EMPTY_STRING = " ";
+ public static final String MESSAGE_DELIMITER = ": -";
+
+ public static final String QUANTITY_UNIT = "๊ฐ";
+
+ public static final String MONEY_UNIT = "์";
+
+ public static final String XMAS_DDAY_DISCOUNT = "ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ";
+ public static final String WEEKDAY_DISCOUNT = "ํ์ผ ํ ์ธ";
+ public static final String WEEKEND_DISCOUNT = "์ฃผ๋ง ํ ์ธ";
+ public static final String SPECIAL_DISCOUNT = "ํน๋ณ ํ ์ธ";
+ public static final String BONUS_EVENT = "์ฆ์ ์ด๋ฒคํธ";
+
+
+ private IOMessage() {
+
+ }
+} | Java | ์์ฑ์๋ฅผ `private`์ผ๋ก ๋ง์๋์ ๋ชจ์ต์ด ๋ณด๊ธฐ ์ข์ต๋๋ค! ๐ |
@@ -0,0 +1,54 @@
+package christmas.controller;
+
+import christmas.domain.entity.Day;
+import christmas.domain.entity.Order;
+import christmas.view.InputView;
+import java.util.function.Supplier;
+
+import static christmas.domain.verifier.RuntimeVerifier.RUNTIME_VERIFIER;
+import static christmas.system.IOMessage.ORDER_PROMPT_MESSAGE;
+import static christmas.system.IOMessage.VISIT_DATE_PROMPT_MESSAGE;
+import static christmas.view.InputView.*;
+import static christmas.view.OutputView.*;
+
+public class PlannerSystem {
+
+ private final Day day;
+ private final Order order;
+ private final SettlementSystem settlementSystem;
+
+ public PlannerSystem() {
+ printMessage(VISIT_DATE_PROMPT_MESSAGE);
+ this.day = readDay();
+ printEventNotice();
+ printMessage(ORDER_PROMPT_MESSAGE);
+ this.order = readOrder(InputView::tryReadOrder);
+ this.settlementSystem = new SettlementSystem(day, order);
+ }
+ public void run() {
+ renderResult();
+ }
+
+ private Order readOrder(Supplier<Order> orderSupplier) {
+ while (true) {
+ try {
+ Order order = orderSupplier.get();
+ RUNTIME_VERIFIER.validate(order);
+ return order;
+ } catch (IllegalStateException e) {
+ printMessage(e.getMessage());
+ }
+ }
+ }
+
+ private void renderResult() {
+ renderPlannerResult();
+ settlementSystem.renderSettlementResult();
+
+ }
+
+ private void renderPlannerResult() {
+ printResultStartMessage(day);
+ printOrderList(order);
+ }
+} | Java | static์ด ์๋๊ฒ ๊ตฌํํด์ ์์กด๊ด๊ณ๋ฅผ ๊ฐ์ง๊ฒ ํด์ผํ ๊น ๊ณ ๋ฏผํด๋ดค์ต๋๋ค. ํ์คํ ์์กด์ฑ ์ฃผ์
์ด ํ์ํ ๊ด๊ณ์ด๋ค ์ถ์๊ฑฐ๋ ์ฃผ์
์ ์์ผฐ๋๋ฐ inputview์ outputview๊น์ง ์์ผ์ผํ๋ ํด์์. ์ํค๋๊ฒ ๋ง์๊น์? |
@@ -0,0 +1,54 @@
+package christmas.controller;
+
+import christmas.domain.entity.Day;
+import christmas.domain.entity.Order;
+import christmas.view.InputView;
+import java.util.function.Supplier;
+
+import static christmas.domain.verifier.RuntimeVerifier.RUNTIME_VERIFIER;
+import static christmas.system.IOMessage.ORDER_PROMPT_MESSAGE;
+import static christmas.system.IOMessage.VISIT_DATE_PROMPT_MESSAGE;
+import static christmas.view.InputView.*;
+import static christmas.view.OutputView.*;
+
+public class PlannerSystem {
+
+ private final Day day;
+ private final Order order;
+ private final SettlementSystem settlementSystem;
+
+ public PlannerSystem() {
+ printMessage(VISIT_DATE_PROMPT_MESSAGE);
+ this.day = readDay();
+ printEventNotice();
+ printMessage(ORDER_PROMPT_MESSAGE);
+ this.order = readOrder(InputView::tryReadOrder);
+ this.settlementSystem = new SettlementSystem(day, order);
+ }
+ public void run() {
+ renderResult();
+ }
+
+ private Order readOrder(Supplier<Order> orderSupplier) {
+ while (true) {
+ try {
+ Order order = orderSupplier.get();
+ RUNTIME_VERIFIER.validate(order);
+ return order;
+ } catch (IllegalStateException e) {
+ printMessage(e.getMessage());
+ }
+ }
+ }
+
+ private void renderResult() {
+ renderPlannerResult();
+ settlementSystem.renderSettlementResult();
+
+ }
+
+ private void renderPlannerResult() {
+ printResultStartMessage(day);
+ printOrderList(order);
+ }
+} | Java | ํ ๋ชฐ๋์ต๋๋ค. ๊ฐ์ฌํฉ๋๋ค.!! |
@@ -0,0 +1,32 @@
+package christmas.controller;
+
+import christmas.domain.entity.Day;
+import christmas.domain.entity.DiscountRecord;
+import christmas.domain.entity.Order;
+import christmas.domain.manager.BonusEventManager;
+import christmas.domain.manager.DiscountManager;
+
+import static christmas.domain.entity.EventBadge.createBadge;
+import static christmas.view.OutputView.*;
+
+public class SettlementSystem {
+
+ private final Order order;
+ private final DiscountRecord discountRecord;
+
+ public SettlementSystem(Day day, Order order) {
+ DiscountManager discountManager = new DiscountManager();
+ BonusEventManager bonusEventManager = new BonusEventManager();
+ this.order = order;
+ this.discountRecord = DiscountRecord.create(day, order, discountManager, bonusEventManager);
+ }
+
+ public void renderSettlementResult() {
+ printOriginalTotalAmount(order);
+ printBonusMenu(order);
+ printDiscountRecord(discountRecord);
+ printTotalDiscountAmount(discountRecord);
+ printExpectedPayment(order, discountRecord);
+ printEventBadge(createBadge(discountRecord));
+ }
+} | Java | ์ด๊ฒ ์ฌ๋ฌ๊ฐ์ง๋ก ๋๋ ๋ณผ๋ ค๊ณ ํ๋๋ฐ ๋๋ฌด ์ด๋ ต๋๋ผ๊ตฌ์... ๋๋ ์ผ ๊น๋ํ ๊ฑฐ ๊ฐ๊ธฐ๋ ํ๋ฐ...
๊ทธ๋ฅ ์ ํฌ๊ฐ plannerSystem์ ๊ตฌํํ๋๊ฑฐ์๊ณ , ๊ธฐ๋ฅ๋ค์ด ๋ค ์ ์ฐ(๊ธ์ต)๊ณผ ๊ด๋ จ๋ ๋ถ๋ถ์ด๋ผ์ settlementSystem์ ๋์์ต๋๋ค. |
@@ -0,0 +1,76 @@
+package christmas.domain.entity;
+
+import static christmas.domain.verifier.VisitDateVerifier.VISIT_DATE_VERIFIER;
+import static christmas.system.Constant.CHRISTMAS;
+import static christmas.system.Constant.FIRST_DAY_OF_MONTH;
+
+public class Day {
+
+ private static final int WEEK_LENGTH = 7;
+ private final int day;
+
+ public Day(int day) {
+ VISIT_DATE_VERIFIER.validateInputInDomain(day);
+ this.day = day;
+ }
+
+ public int getDay() {
+ return day;
+ }
+
+ public boolean isChristmasSeason() {
+ if (day >= FIRST_DAY_OF_MONTH && day <= CHRISTMAS) {
+ return true;
+ }
+ return false;
+ }
+
+ public boolean isWeekday() {
+ if (!(isFriday() || isSaturday())) {
+ return true;
+ }
+ return false;
+ }
+
+ public boolean isWeekend() {
+ if (isFriday() || isSaturday()) {
+ return true;
+ }
+ return false;
+ }
+
+ public boolean isSpecialDay() {
+ if (isSunday() || isChristmas()) {
+ return true;
+ }
+ return false;
+ }
+
+ private boolean isFriday() {
+ if (day % WEEK_LENGTH == 1) {
+ return true;
+ }
+ return false;
+ }
+
+ private boolean isSaturday() {
+ if (day % WEEK_LENGTH == 2) {
+ return true;
+ }
+ return false;
+ }
+
+ private boolean isSunday() {
+ if (day % WEEK_LENGTH == 3) {
+ return true;
+ }
+ return false;
+ }
+
+ private boolean isChristmas() {
+ if (day == CHRISTMAS) {
+ return true;
+ }
+ return false;
+ }
+} | Java | ๋ฉ์๋๋ช
์ ์ ๋ง ์ ์ง์ผ์ ๊ฑฐ ๊ฐ์์! ๐ |
@@ -0,0 +1,48 @@
+package christmas.domain.entity;
+
+import christmas.domain.util.Util;
+
+import java.util.Arrays;
+
+import static christmas.system.IOMessage.EMPTY_STRING;
+import static christmas.system.IOMessage.QUANTITY_UNIT;
+
+public enum BonusMenu {
+ CHAMPAGNE(Menu.CHAMPAGNE, 1);
+
+ private final Menu menu;
+ private final int quantity;
+
+ BonusMenu(Menu menu, int quantity) {
+ this.menu = menu;
+ this.quantity = quantity;
+ }
+
+ public static int calculateTotalPriceForAllMenus() {
+ return Arrays.stream(BonusMenu.values())
+ .mapToInt(BonusMenu::getTotalPrice)
+ .sum();
+ }
+
+ public static String generateAllMenuDetails() {
+ StringBuilder stringBuilder = new StringBuilder();
+ for (BonusMenu bonusMenu : BonusMenu.values()) {
+ stringBuilder.append(bonusMenu.toString()).append(System.lineSeparator());
+ }
+ return stringBuilder.toString();
+ }
+
+ @Override
+ public String toString() {
+ return getName() + EMPTY_STRING + Util.createFormattedAmount(quantity) + QUANTITY_UNIT;
+ }
+
+ private String getName() {
+ return menu.getMenuName();
+ }
+
+ private int getTotalPrice() {
+ return menu.getMenuPrice() * quantity;
+ }
+
+} | Java | ์ฒ์์๋ ๊ทธ๋ฐ ๋ฐฉ์์ผ๋ก ํ์๋๋ฐ,
๊ฐ ํด๋์ค์์, ํด๋์ค์ ๋ํด ์ถ๋ ฅํ ์ ๋ณด๋ฅผ ๋ง๋๋๊ฑฐ๊น์ง๋ ๊ฐ์ฒด๊ฐ ๋ด๋นํด์ผํ ๋ชซ์ด์ง ์์๊น ํด์ ๋ฐ๊ฟจ์์ด์...
์ถ๋ ฅ์ outputview์์ ํฉ๋๋ค. ์ด ๋ถ๋ถ์ ๋ค๋ฅธ๋ถ๋ถ์ ์๊ฒฌ๋ ๋ฃ๊ณ ์ถ์ด์!!
1. outputview์์ getter๊ฐ ์๋๋๋ผ๋, ์ธ์๋ฅผ ํตํด ์ถ๋ ฅํ ํด๋์ค์ ์ ๋ณด๋ฅผ ๊บผ๋ด์ ์ถ๋ ฅ ๋ฉ์์ง๋ฅผ ๋ง๋ค๊ณ ์ถ๋ ฅ๊น์ง ํ๋๊ฑธ ๋ด๋นํด์ผํ ๊น?
2. ์ถ๋ ฅํด์ผํ ํด๋์ค์ ์ ๋ณด๋ ํด๋์ค ๋ด์์ ๋ง๋ค๊ณ , ์ถ๋ ฅ๋ง outputview์์ ํด์ผํ๋๊ฒ ๋ง์๊น์? |
@@ -0,0 +1,12 @@
+package christmas.domain.util;
+
+
+import java.text.DecimalFormat;
+
+public final class Util {
+ public static String createFormattedAmount(int target) {
+ DecimalFormat formatter = new DecimalFormat("###,##0");
+ return formatter.format(target);
+ }
+
+} | Java | ์ฐธ๊ณ ํ๊ฒ ์ต๋๋ค. ๋๋ฌด๋๋ฌด ํผ๋๋ฐฑ ์ด์ฌํ ํด์ฃผ์
์ ๊ฐ์ฌํด์ ์์ฌ๋ ๐ |
@@ -0,0 +1,76 @@
+package christmas.domain.entity;
+
+import static christmas.domain.verifier.VisitDateVerifier.VISIT_DATE_VERIFIER;
+import static christmas.system.Constant.CHRISTMAS;
+import static christmas.system.Constant.FIRST_DAY_OF_MONTH;
+
+public class Day {
+
+ private static final int WEEK_LENGTH = 7;
+ private final int day;
+
+ public Day(int day) {
+ VISIT_DATE_VERIFIER.validateInputInDomain(day);
+ this.day = day;
+ }
+
+ public int getDay() {
+ return day;
+ }
+
+ public boolean isChristmasSeason() {
+ if (day >= FIRST_DAY_OF_MONTH && day <= CHRISTMAS) {
+ return true;
+ }
+ return false;
+ }
+
+ public boolean isWeekday() {
+ if (!(isFriday() || isSaturday())) {
+ return true;
+ }
+ return false;
+ }
+
+ public boolean isWeekend() {
+ if (isFriday() || isSaturday()) {
+ return true;
+ }
+ return false;
+ }
+
+ public boolean isSpecialDay() {
+ if (isSunday() || isChristmas()) {
+ return true;
+ }
+ return false;
+ }
+
+ private boolean isFriday() {
+ if (day % WEEK_LENGTH == 1) {
+ return true;
+ }
+ return false;
+ }
+
+ private boolean isSaturday() {
+ if (day % WEEK_LENGTH == 2) {
+ return true;
+ }
+ return false;
+ }
+
+ private boolean isSunday() {
+ if (day % WEEK_LENGTH == 3) {
+ return true;
+ }
+ return false;
+ }
+
+ private boolean isChristmas() {
+ if (day == CHRISTMAS) {
+ return true;
+ }
+ return false;
+ }
+} | Java | ๊ฐ์ธ์ ์ธ ์๊ฒฌ์ธ๋ฐ, `isFriday() || isSaturday()`๊ฐ `isWeekend()`๋ฉ์๋์ ๋๊ฐ์ผ๋, ์ด๊ฑธ ํ์ฉํ๋๊ฒ ์ด๋จ๊น์?
```java
public boolean isWeekday() {
return !isWeekend();
}
```
์ด๋ ๊ฒ์! ๐ |
@@ -0,0 +1,59 @@
+package christmas.domain.entity;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static christmas.domain.entity.MenuType.*;
+
+public enum Menu {
+
+ MUSHROOM_SOUP("์์ก์ด์ํ", 6_000, APPETIZER),
+ TAPAS("ํํ์ค", 5_500, APPETIZER),
+ CAESAR_SALAD("์์ ์๋ฌ๋", 8_000, APPETIZER),
+
+ T_BONE_STEAK("ํฐ๋ณธ์คํ
์ดํฌ", 55_000, MAIN),
+ BBQ_RIBS("๋ฐ๋นํ๋ฆฝ", 54_000, MAIN),
+ SEAFOOD_PASTA("ํด์ฐ๋ฌผํ์คํ", 35_000, MAIN),
+ CHRISTMAS_PASTA("ํฌ๋ฆฌ์ค๋ง์คํ์คํ", 25_000, MAIN),
+
+ CHOCOLATE_CAKE("์ด์ฝ์ผ์ดํฌ", 15_000, DESSERT),
+ ICE_CREAM("์์ด์คํฌ๋ฆผ", 5_000, DESSERT),
+
+ ZERO_COLA("์ ๋ก์ฝ๋ผ", 3_000, BEVERAGE),
+ RED_WINE("๋ ๋์์ธ", 60_000, BEVERAGE),
+ CHAMPAGNE("์ดํ์ธ", 25_000, BEVERAGE);
+
+ private static final Map<String, Menu> MENU_MAP = new HashMap<>();
+ private final String menuName;
+ private final int price;
+ private final MenuType menuType;
+
+ Menu(String menuName, int price, MenuType menuType) {
+ this.menuName = menuName;
+ this.price = price;
+ this.menuType = menuType;
+ }
+
+ static {
+ for (Menu menu : Menu.values()) {
+ MENU_MAP.put(menu.menuName, menu);
+ }
+ }
+
+ public static Menu getMenuItemByName(String menuName) {
+ return MENU_MAP.get(menuName);
+ }
+
+ public String getMenuName() {
+ return menuName;
+ }
+
+ public int getMenuPrice() {
+ return price;
+ }
+
+ public MenuType getMenuType() {
+ return menuType;
+ }
+
+} | Java | ๋ฐ๋ก `HashMap`์ ๋ง๋ค์ด ๋ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค! `getMenuItemByName`๋ฉ์๋์์ ๊ฒ์์๋๋ฅผ ๋์ด๊ธฐ ์ํจ์ธ๊ฐ์? |
@@ -0,0 +1,12 @@
+package christmas.domain.util;
+
+
+import java.text.DecimalFormat;
+
+public final class Util {
+ public static String createFormattedAmount(int target) {
+ DecimalFormat formatter = new DecimalFormat("###,##0");
+ return formatter.format(target);
+ }
+
+} | Java | split์ ํ ๊ฒฐ๊ณผ๊ฐ ์ฌ์ด์ฆ๊ฐ 1์ด์ด์ `orderItemSpec[1]`์ ์ ๊ทผ์ด `IndexOutOfBoundsException`์ ์ผ์ผํฌ ๊ฒฝ์ฐ๋ ์๋์? ์ด๋ฅผ ์ผ๋ํด๋์
จ๋๋ฉด ์ด๋ป๊ฒ ๊ฒ์ฆ์ ํ์
จ๋์ง ๊ถ๊ธํฉ๋๋ค! |
@@ -0,0 +1,96 @@
+package christmas.domain.verifier;
+
+
+import christmas.domain.entity.Menu;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import static christmas.system.ExceptionMessage.*;
+
+public class OrderMenuVerifier implements Verifier<String> {
+
+ public static final OrderMenuVerifier ORDER_MENU_VERIFIER = new OrderMenuVerifier();
+
+ private final Pattern pattern;
+
+ private OrderMenuVerifier() {
+ this.pattern = Pattern.compile("[๊ฐ-ํฃ]+-\\d+(,[๊ฐ-ํฃ]+-\\d+)*");
+ }
+
+ @Override
+ public void validate(final String input) {
+ validateMenuFormat(input);
+ }
+
+ public void validateInputInDomain(final String input) {
+ validateMenuExistence(input);
+ validateDistinctMenu(input);
+ validateMenuQuantity(input);
+ }
+
+ private void validateMenuFormat(final String input) {
+ String[] orders = input.split(",");
+ for (String order : orders) {
+ validateOrderFormat(order);
+ }
+ }
+
+ private void validateMenuExistence(final String input) {
+ String[] orders = input.split(",");
+ for (String order : orders) {
+ validateOrderExistence(order);
+ }
+ }
+
+ private void validateDistinctMenu(final String input) {
+ Set<String> uniqueMenuItems = new HashSet<>();
+ String[] orders = input.split(",");
+ for (String order : orders) {
+ validateDistinctMenu(order, uniqueMenuItems);
+ }
+ }
+
+ private void validateMenuQuantity(final String input) {
+ String[] orders = input.split(",");
+ for (String order : orders) {
+ validateOrderQuantity(order);
+ }
+ }
+
+ private void validateOrderFormat(final String order) {
+ Matcher matcher = pattern.matcher(order);
+ if (!matcher.matches()) {
+ Verifier.throwIllegalArgumentError(INVALID_ORDER_MESSAGE);
+ }
+ }
+
+ private void validateOrderExistence(final String order) {
+ String[] orderInfo = order.split("-");
+ if (Menu.getMenuItemByName(orderInfo[0]) == null) {
+ Verifier.throwIllegalArgumentError(INVALID_ORDER_MESSAGE);
+ }
+ }
+
+ private void validateDistinctMenu(final String order, Set<String> uniqueMenuItems) {
+ String[] orderInfo = order.split("-");
+ if (!uniqueMenuItems.add(orderInfo[0])) {
+ Verifier.throwIllegalArgumentError(INVALID_ORDER_MESSAGE);
+ }
+ }
+
+ private void validateOrderQuantity(final String order) {
+ String[] orderInfo = order.split("-");
+ try {
+ int quantity = Integer.parseInt(orderInfo[1]);
+ if (quantity < 1) {
+ Verifier.throwIllegalArgumentError(INVALID_ORDER_MESSAGE);
+ }
+ } catch (NumberFormatException e) {
+ Verifier.throwIllegalArgumentError(INVALID_ORDER_MESSAGE);
+ }
+ }
+
+
+} | Java | ๋ฐ๋ก ์ธ์์ ๋ฐ๋ผ์ ํจํด์ด ๋ฌ๋ผ์ง๋ ๊ฒ ๊ฐ์ง ์์๋ฐ, ํ๋์์ ๋ฐ๋ก ์ด๊ธฐํํ์ง ์๊ณ , ์์ฑ์ ๋ด๋ถ์์ ์ด๊ธฐํํ์ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค! ๋ญ๊ฐ ๋ ์ข์ ๋ฐฉ๋ฒ์ธ์ง ์ ๋ ์ ๋ชจ๋ฅด๊ฒ ์ด์.. ๐ |
@@ -0,0 +1,14 @@
+package christmas.domain.verifier;
+
+public interface Verifier<T> {
+
+ abstract public void validate(T input);
+
+ static void throwIllegalArgumentError(String errorMessage) {
+ throw new IllegalArgumentException(errorMessage);
+ }
+
+ static void throwIllegalStateError(String errorMessage) {
+ throw new IllegalStateException(errorMessage);
+ }
+} | Java | ์ด ์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํ ํด๋์ค๋ค์ `check`๋ง ์ฌ์ฉํ๋ฉด ํ์ํ ๊ฒ์ฆ์ด ๋ค ๋๋ ๋ฐฉ์์ด๋ค์! ๊น๋ํ๊ณ ์ข๋ค์! ๐ |
@@ -0,0 +1,59 @@
+package christmas.domain.entity;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static christmas.domain.entity.MenuType.*;
+
+public enum Menu {
+
+ MUSHROOM_SOUP("์์ก์ด์ํ", 6_000, APPETIZER),
+ TAPAS("ํํ์ค", 5_500, APPETIZER),
+ CAESAR_SALAD("์์ ์๋ฌ๋", 8_000, APPETIZER),
+
+ T_BONE_STEAK("ํฐ๋ณธ์คํ
์ดํฌ", 55_000, MAIN),
+ BBQ_RIBS("๋ฐ๋นํ๋ฆฝ", 54_000, MAIN),
+ SEAFOOD_PASTA("ํด์ฐ๋ฌผํ์คํ", 35_000, MAIN),
+ CHRISTMAS_PASTA("ํฌ๋ฆฌ์ค๋ง์คํ์คํ", 25_000, MAIN),
+
+ CHOCOLATE_CAKE("์ด์ฝ์ผ์ดํฌ", 15_000, DESSERT),
+ ICE_CREAM("์์ด์คํฌ๋ฆผ", 5_000, DESSERT),
+
+ ZERO_COLA("์ ๋ก์ฝ๋ผ", 3_000, BEVERAGE),
+ RED_WINE("๋ ๋์์ธ", 60_000, BEVERAGE),
+ CHAMPAGNE("์ดํ์ธ", 25_000, BEVERAGE);
+
+ private static final Map<String, Menu> MENU_MAP = new HashMap<>();
+ private final String menuName;
+ private final int price;
+ private final MenuType menuType;
+
+ Menu(String menuName, int price, MenuType menuType) {
+ this.menuName = menuName;
+ this.price = price;
+ this.menuType = menuType;
+ }
+
+ static {
+ for (Menu menu : Menu.values()) {
+ MENU_MAP.put(menu.menuName, menu);
+ }
+ }
+
+ public static Menu getMenuItemByName(String menuName) {
+ return MENU_MAP.get(menuName);
+ }
+
+ public String getMenuName() {
+ return menuName;
+ }
+
+ public int getMenuPrice() {
+ return price;
+ }
+
+ public MenuType getMenuType() {
+ return menuType;
+ }
+
+} | Java | ๋ค ๋ง์์! HashMap์ ์ฌ์ฉํ๋ฉด ๊ฒ์์๋๊ฐ O(1)์ ๊ฐ๊น์ด ์๋๋ก ๋งค์ฐ ํฅ์๋๋ค๊ณ ํฉ๋๋ค.!! |
@@ -0,0 +1,96 @@
+package christmas.domain.verifier;
+
+
+import christmas.domain.entity.Menu;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import static christmas.system.ExceptionMessage.*;
+
+public class OrderMenuVerifier implements Verifier<String> {
+
+ public static final OrderMenuVerifier ORDER_MENU_VERIFIER = new OrderMenuVerifier();
+
+ private final Pattern pattern;
+
+ private OrderMenuVerifier() {
+ this.pattern = Pattern.compile("[๊ฐ-ํฃ]+-\\d+(,[๊ฐ-ํฃ]+-\\d+)*");
+ }
+
+ @Override
+ public void validate(final String input) {
+ validateMenuFormat(input);
+ }
+
+ public void validateInputInDomain(final String input) {
+ validateMenuExistence(input);
+ validateDistinctMenu(input);
+ validateMenuQuantity(input);
+ }
+
+ private void validateMenuFormat(final String input) {
+ String[] orders = input.split(",");
+ for (String order : orders) {
+ validateOrderFormat(order);
+ }
+ }
+
+ private void validateMenuExistence(final String input) {
+ String[] orders = input.split(",");
+ for (String order : orders) {
+ validateOrderExistence(order);
+ }
+ }
+
+ private void validateDistinctMenu(final String input) {
+ Set<String> uniqueMenuItems = new HashSet<>();
+ String[] orders = input.split(",");
+ for (String order : orders) {
+ validateDistinctMenu(order, uniqueMenuItems);
+ }
+ }
+
+ private void validateMenuQuantity(final String input) {
+ String[] orders = input.split(",");
+ for (String order : orders) {
+ validateOrderQuantity(order);
+ }
+ }
+
+ private void validateOrderFormat(final String order) {
+ Matcher matcher = pattern.matcher(order);
+ if (!matcher.matches()) {
+ Verifier.throwIllegalArgumentError(INVALID_ORDER_MESSAGE);
+ }
+ }
+
+ private void validateOrderExistence(final String order) {
+ String[] orderInfo = order.split("-");
+ if (Menu.getMenuItemByName(orderInfo[0]) == null) {
+ Verifier.throwIllegalArgumentError(INVALID_ORDER_MESSAGE);
+ }
+ }
+
+ private void validateDistinctMenu(final String order, Set<String> uniqueMenuItems) {
+ String[] orderInfo = order.split("-");
+ if (!uniqueMenuItems.add(orderInfo[0])) {
+ Verifier.throwIllegalArgumentError(INVALID_ORDER_MESSAGE);
+ }
+ }
+
+ private void validateOrderQuantity(final String order) {
+ String[] orderInfo = order.split("-");
+ try {
+ int quantity = Integer.parseInt(orderInfo[1]);
+ if (quantity < 1) {
+ Verifier.throwIllegalArgumentError(INVALID_ORDER_MESSAGE);
+ }
+ } catch (NumberFormatException e) {
+ Verifier.throwIllegalArgumentError(INVALID_ORDER_MESSAGE);
+ }
+ }
+
+
+} | Java | ์ ๋ ๋ญ๊ฐ ๋ ์ข์ ๋ฐฉ๋ฒ์ธ์ง ๋ชฐ๋ผ์ ์ฐพ์๋ดค์๋๋ฐ,
์์ฑ์์์ ์ด๊ธฐํ๋ฅผ ํ๋ฉด, ์์ฑ์ ์์ ํจ์์ ๋ํ ์์ธ์ฒ๋ฆฌ๊ฐ ๊ฐ๋ฅํด์ง๊ณ , ์ธ๋ถ์์ ๋ค๋ฅธ pattern๊ฐ์ฒด๋ฅผ ์ฃผ์
ํ๊ธฐ๊ฐ ์ฌ์์ง๋ค๊ณ ํ๋๋ผ๊ตฌ์.
๋ฐ๋ฉด์ ํ๋์์ ์ด๊ธฐํํ๋ฉด ๊ฐ๋
์ฑ๊ณผ ๊ฐ๊ฒฐํจ์ด ์ฅ์ ์ด์ฃ .
์์ฑ์์์์ ์์ธ์ฒ๋ฆฌ ๋ก์ง์ด ์์ง๋ง ์ด๋ ๊ฒ๋ ํ๋ฒ ํด๋ดค์ด์! ์ํฉ์ ๋ฐ๋ผ์ ๋ค๋ฅด๊ฒ ํด๋ณด๋ฉด ์ข์๊ฑฐ ๊ฐ์์!! |
@@ -0,0 +1,14 @@
+package christmas.domain.verifier;
+
+public interface Verifier<T> {
+
+ abstract public void validate(T input);
+
+ static void throwIllegalArgumentError(String errorMessage) {
+ throw new IllegalArgumentException(errorMessage);
+ }
+
+ static void throwIllegalStateError(String errorMessage) {
+ throw new IllegalStateException(errorMessage);
+ }
+} | Java | ํผ๋๋ฐฑ ์ ๋ง ๊ฐ์ฌํด์! ์ธ์
๋๋ ํฌ๋ฆฌ์ค๋ง์ค ์ฝ๋ ๋ฆฌ๋ทฐ ํด๋๋ฆด๋ ค๊ณ ํ๋๋ฐ repository๊ฐ private์ธ๊ฐ๋ด์๐ |
@@ -0,0 +1,76 @@
+package christmas.domain.entity;
+
+import static christmas.domain.verifier.VisitDateVerifier.VISIT_DATE_VERIFIER;
+import static christmas.system.Constant.CHRISTMAS;
+import static christmas.system.Constant.FIRST_DAY_OF_MONTH;
+
+public class Day {
+
+ private static final int WEEK_LENGTH = 7;
+ private final int day;
+
+ public Day(int day) {
+ VISIT_DATE_VERIFIER.validateInputInDomain(day);
+ this.day = day;
+ }
+
+ public int getDay() {
+ return day;
+ }
+
+ public boolean isChristmasSeason() {
+ if (day >= FIRST_DAY_OF_MONTH && day <= CHRISTMAS) {
+ return true;
+ }
+ return false;
+ }
+
+ public boolean isWeekday() {
+ if (!(isFriday() || isSaturday())) {
+ return true;
+ }
+ return false;
+ }
+
+ public boolean isWeekend() {
+ if (isFriday() || isSaturday()) {
+ return true;
+ }
+ return false;
+ }
+
+ public boolean isSpecialDay() {
+ if (isSunday() || isChristmas()) {
+ return true;
+ }
+ return false;
+ }
+
+ private boolean isFriday() {
+ if (day % WEEK_LENGTH == 1) {
+ return true;
+ }
+ return false;
+ }
+
+ private boolean isSaturday() {
+ if (day % WEEK_LENGTH == 2) {
+ return true;
+ }
+ return false;
+ }
+
+ private boolean isSunday() {
+ if (day % WEEK_LENGTH == 3) {
+ return true;
+ }
+ return false;
+ }
+
+ private boolean isChristmas() {
+ if (day == CHRISTMAS) {
+ return true;
+ }
+ return false;
+ }
+} | Java | ์ค... ๊ฐ์ฌํฉ๋๋ค.! ๋ฆฌํํ ๋ง ํด๋ณผ๊ฒ์ |
@@ -0,0 +1,12 @@
+package christmas.domain.util;
+
+
+import java.text.DecimalFormat;
+
+public final class Util {
+ public static String createFormattedAmount(int target) {
+ DecimalFormat formatter = new DecimalFormat("###,##0");
+ return formatter.format(target);
+ }
+
+} | Java | ์๋ฅผ๋ค์ด,
Input: ์ดํ์ธ-
์ด๋ ๊ฒ ์
๋ ฅ๋ ๊ฒฝ์ฐ, orderMenuVerifier์ checkMenuFormat ๋ฉ์๋์ ์ํด ์ฌ๋ฐ๋ฅธ ๋ฉ๋ด ํ์์ด ์๋ ์์ธ์ฒ๋ฆฌ๊ฐ ๋์ด์ ธ๋ฒ๋ ค
์์ Util๋ฉ์๋๋ฅผ ํธ์ถํ๋ ๊ฒฝ์ฐ๊ฐ ์๋๋ก ๊ตฌํํ์ต๋๋ค.
<img width="474" alt="image" src="https://github.com/Hoo-sung/java-christmas-6-Hoo-sung/assets/121723421/e2a0a147-e665-4a6a-94ce-3876632e0d0b">
์ด๋ ๊ฒ orderMenuVerifier๋ก ๊ฒ์ฆ์ ๋ง์น๊ณ Util class๋ฅผ ์ด์ฉํด์ order๊ฐ์ฒด๋ฅผ ๋ฐํํ๋๋ก ํ์ต๋๋ค. |
@@ -1,152 +1,44 @@
package com.example.project.compile.service;
+import com.example.project.compile.domain.CompileLanguage;
import com.example.project.error.dto.ErrorMessage;
-import org.springframework.beans.factory.annotation.Value;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.IOException;
-import java.nio.file.*;
-import java.util.UUID;
+import java.nio.file.Files;
+import java.nio.file.Path;
+@Slf4j
@Service
+@RequiredArgsConstructor
public class CompileService {
- private final String code_dir;
- public CompileService(@Value("${compile.url}") String codeDir) {
- this.code_dir = codeDir;
- }
+ private final FileService fileService;
+ private final CommandExecutorService commandExecutorService;
- public String compileAndRun(String language, String code) throws IOException, InterruptedException {
+ public String compileAndRun(String language, String code, String codeDir) throws IOException {
+ CompileLanguage compileLanguage = CompileLanguage.JAVA.getByLanguageName(language);
+ Path filePath = null;
try {
- Path codePath = Paths.get(code_dir);
- if (!Files.exists(codePath)) {
- Files.createDirectories(codePath);
+ filePath = fileService.createCodeFile(code, compileLanguage, codeDir);
+ return executeCode(filePath);
+ } finally {
+ if (filePath != null) {
+ Files.deleteIfExists(filePath);
}
-
- String filename = generateFileName(language);
- Path filePath = codePath.resolve(filename);
-
- Files.write(filePath, code.getBytes());
-
- return executeCode(language, filePath, codePath);
- } catch (FileAlreadyExistsException e) {
- throw new IOException(ErrorMessage.CODE_DIRECTORY_CREATION_FAILED.getMessage(), e);
- } catch (IOException e) {
- throw new IOException(ErrorMessage.CODE_WRITE_FAILED.getMessage(), e);
}
}
- private String executeCode(String language, Path filePath, Path codePath) throws IOException, InterruptedException {
+ private String executeCode(Path filePath) throws IOException {
+ String result;
try {
- //TODO Enum ์ฌ์ฉํ๊ธฐ
- return switch (language.toLowerCase()) {
- case "c" -> compileAndRun(filePath, "gcc", codePath.resolve("output").toString(), "");
- case "java" -> compileJava(filePath);
- case "python" -> compilePython(filePath);
- default -> throw new IllegalArgumentException(ErrorMessage.UNSUPPORTED_LANGUAGE.getMessage());
- };
- } catch (IllegalArgumentException e) {
- throw new IllegalArgumentException(ErrorMessage.UNSUPPORTED_LANGUAGE.getMessage(), e);
+ String command = filePath.getParent().resolve("output").toString();
+ result = commandExecutorService.runCommand(command);
} catch (IOException | InterruptedException e) {
throw new IOException(ErrorMessage.GENERAL_COMPILE_ERROR.getMessage(), e);
}
- }
-
- private String compileAndRun(Path filePath, String compiler, String outputFileName, String additionalArgs) throws IOException, InterruptedException {
- String command = String.format("%s %s -o %s %s", compiler, filePath, outputFileName, additionalArgs);
- Process compileProcess = Runtime.getRuntime().exec(command);
- compileProcess.waitFor();
-
- if (compileProcess.exitValue() == 0) {
- return runCompiledProgram(outputFileName);
- } else {
- String errorOutput = new String(compileProcess.getErrorStream().readAllBytes());
- throw new IOException(ErrorMessage.COMPILATION_FAILED.getMessage() + "\n" + errorOutput);
- }
- }
-
- private String runCompiledProgram(String outputFileName) throws IOException, InterruptedException {
- Process runProcess = Runtime.getRuntime().exec(outputFileName);
- runProcess.waitFor();
-
- if (runProcess.exitValue() == 0) {
- return new String(runProcess.getInputStream().readAllBytes());
- } else {
- String errorOutput = new String(runProcess.getErrorStream().readAllBytes());
- throw new IOException(ErrorMessage.EXECUTION_FAILED.getMessage() + "\n" + errorOutput);
- }
- }
-
- private String compileJava(Path filePath) throws IOException, InterruptedException {
- String className = extractClassName(filePath);
- Path correctFilePath = filePath.getParent().resolve(className + ".java");
-
- try {
- Files.move(filePath, correctFilePath, StandardCopyOption.REPLACE_EXISTING);
- } catch (FileAlreadyExistsException e) {
- throw new IOException(ErrorMessage.JAVA_FILE_RENAMING_FAILED.getMessage(), e);
- }
-
- String command = String.format("javac %s", correctFilePath);
- Process compileProcess = Runtime.getRuntime().exec(command);
- compileProcess.waitFor();
-
- if (compileProcess.exitValue() == 0) {
- return runJavaProgram(correctFilePath);
- } else {
- String errorOutput = new String(compileProcess.getErrorStream().readAllBytes());
- throw new IOException(ErrorMessage.COMPILATION_FAILED.getMessage() + "\n" + errorOutput);
- }
- }
-
- private String extractClassName(Path filePath) throws IOException {
- try {
- String content = Files.readString(filePath);
- return content.split("public class ")[1].split("\\s")[0].trim();
- } catch (Exception e) {
- throw new IOException(ErrorMessage.JAVA_CLASS_EXTRACTION_FAILED.getMessage(), e);
- }
- }
-
- private String runJavaProgram(Path filePath) throws IOException, InterruptedException {
- String className = filePath.getFileName().toString().replace(".java", "");
- String runCommand = String.format("java -cp %s %s", filePath.getParent(), className);
-
- Process runProcess = Runtime.getRuntime().exec(runCommand);
- runProcess.waitFor();
-
- if (runProcess.exitValue() == 0) {
- return new String(runProcess.getInputStream().readAllBytes());
- } else {
- String errorOutput = new String(runProcess.getErrorStream().readAllBytes());
- throw new IOException(ErrorMessage.EXECUTION_FAILED.getMessage() + "\n" + errorOutput);
- }
- }
-
- private String compilePython(Path filePath) throws IOException, InterruptedException {
- String command = String.format("python %s", filePath);
- Process process = Runtime.getRuntime().exec(command);
- process.waitFor();
-
- if (process.exitValue() == 0) {
- return new String(process.getInputStream().readAllBytes());
- } else {
- String errorOutput = new String(process.getErrorStream().readAllBytes());
- throw new IOException(ErrorMessage.EXECUTION_FAILED.getMessage() + "\n" + errorOutput);
- }
- }
-
- private String generateFileName(String language) {
- return UUID.randomUUID() + getExtension(language);
- }
-
- private String getExtension(String language) {
- //TODO ENUM
- return switch (language.toLowerCase()) {
- case "c" -> ".c";
- case "java" -> ".java";
- case "python" -> ".py";
- default -> throw new IllegalArgumentException(ErrorMessage.UNSUPPORTED_LANGUAGE.getMessage());
- };
+ return result;
}
}
\ No newline at end of file | Java | enum์ ์ฌ์ฉํฉ์๋ค |
@@ -1,152 +1,44 @@
package com.example.project.compile.service;
+import com.example.project.compile.domain.CompileLanguage;
import com.example.project.error.dto.ErrorMessage;
-import org.springframework.beans.factory.annotation.Value;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.IOException;
-import java.nio.file.*;
-import java.util.UUID;
+import java.nio.file.Files;
+import java.nio.file.Path;
+@Slf4j
@Service
+@RequiredArgsConstructor
public class CompileService {
- private final String code_dir;
- public CompileService(@Value("${compile.url}") String codeDir) {
- this.code_dir = codeDir;
- }
+ private final FileService fileService;
+ private final CommandExecutorService commandExecutorService;
- public String compileAndRun(String language, String code) throws IOException, InterruptedException {
+ public String compileAndRun(String language, String code, String codeDir) throws IOException {
+ CompileLanguage compileLanguage = CompileLanguage.JAVA.getByLanguageName(language);
+ Path filePath = null;
try {
- Path codePath = Paths.get(code_dir);
- if (!Files.exists(codePath)) {
- Files.createDirectories(codePath);
+ filePath = fileService.createCodeFile(code, compileLanguage, codeDir);
+ return executeCode(filePath);
+ } finally {
+ if (filePath != null) {
+ Files.deleteIfExists(filePath);
}
-
- String filename = generateFileName(language);
- Path filePath = codePath.resolve(filename);
-
- Files.write(filePath, code.getBytes());
-
- return executeCode(language, filePath, codePath);
- } catch (FileAlreadyExistsException e) {
- throw new IOException(ErrorMessage.CODE_DIRECTORY_CREATION_FAILED.getMessage(), e);
- } catch (IOException e) {
- throw new IOException(ErrorMessage.CODE_WRITE_FAILED.getMessage(), e);
}
}
- private String executeCode(String language, Path filePath, Path codePath) throws IOException, InterruptedException {
+ private String executeCode(Path filePath) throws IOException {
+ String result;
try {
- //TODO Enum ์ฌ์ฉํ๊ธฐ
- return switch (language.toLowerCase()) {
- case "c" -> compileAndRun(filePath, "gcc", codePath.resolve("output").toString(), "");
- case "java" -> compileJava(filePath);
- case "python" -> compilePython(filePath);
- default -> throw new IllegalArgumentException(ErrorMessage.UNSUPPORTED_LANGUAGE.getMessage());
- };
- } catch (IllegalArgumentException e) {
- throw new IllegalArgumentException(ErrorMessage.UNSUPPORTED_LANGUAGE.getMessage(), e);
+ String command = filePath.getParent().resolve("output").toString();
+ result = commandExecutorService.runCommand(command);
} catch (IOException | InterruptedException e) {
throw new IOException(ErrorMessage.GENERAL_COMPILE_ERROR.getMessage(), e);
}
- }
-
- private String compileAndRun(Path filePath, String compiler, String outputFileName, String additionalArgs) throws IOException, InterruptedException {
- String command = String.format("%s %s -o %s %s", compiler, filePath, outputFileName, additionalArgs);
- Process compileProcess = Runtime.getRuntime().exec(command);
- compileProcess.waitFor();
-
- if (compileProcess.exitValue() == 0) {
- return runCompiledProgram(outputFileName);
- } else {
- String errorOutput = new String(compileProcess.getErrorStream().readAllBytes());
- throw new IOException(ErrorMessage.COMPILATION_FAILED.getMessage() + "\n" + errorOutput);
- }
- }
-
- private String runCompiledProgram(String outputFileName) throws IOException, InterruptedException {
- Process runProcess = Runtime.getRuntime().exec(outputFileName);
- runProcess.waitFor();
-
- if (runProcess.exitValue() == 0) {
- return new String(runProcess.getInputStream().readAllBytes());
- } else {
- String errorOutput = new String(runProcess.getErrorStream().readAllBytes());
- throw new IOException(ErrorMessage.EXECUTION_FAILED.getMessage() + "\n" + errorOutput);
- }
- }
-
- private String compileJava(Path filePath) throws IOException, InterruptedException {
- String className = extractClassName(filePath);
- Path correctFilePath = filePath.getParent().resolve(className + ".java");
-
- try {
- Files.move(filePath, correctFilePath, StandardCopyOption.REPLACE_EXISTING);
- } catch (FileAlreadyExistsException e) {
- throw new IOException(ErrorMessage.JAVA_FILE_RENAMING_FAILED.getMessage(), e);
- }
-
- String command = String.format("javac %s", correctFilePath);
- Process compileProcess = Runtime.getRuntime().exec(command);
- compileProcess.waitFor();
-
- if (compileProcess.exitValue() == 0) {
- return runJavaProgram(correctFilePath);
- } else {
- String errorOutput = new String(compileProcess.getErrorStream().readAllBytes());
- throw new IOException(ErrorMessage.COMPILATION_FAILED.getMessage() + "\n" + errorOutput);
- }
- }
-
- private String extractClassName(Path filePath) throws IOException {
- try {
- String content = Files.readString(filePath);
- return content.split("public class ")[1].split("\\s")[0].trim();
- } catch (Exception e) {
- throw new IOException(ErrorMessage.JAVA_CLASS_EXTRACTION_FAILED.getMessage(), e);
- }
- }
-
- private String runJavaProgram(Path filePath) throws IOException, InterruptedException {
- String className = filePath.getFileName().toString().replace(".java", "");
- String runCommand = String.format("java -cp %s %s", filePath.getParent(), className);
-
- Process runProcess = Runtime.getRuntime().exec(runCommand);
- runProcess.waitFor();
-
- if (runProcess.exitValue() == 0) {
- return new String(runProcess.getInputStream().readAllBytes());
- } else {
- String errorOutput = new String(runProcess.getErrorStream().readAllBytes());
- throw new IOException(ErrorMessage.EXECUTION_FAILED.getMessage() + "\n" + errorOutput);
- }
- }
-
- private String compilePython(Path filePath) throws IOException, InterruptedException {
- String command = String.format("python %s", filePath);
- Process process = Runtime.getRuntime().exec(command);
- process.waitFor();
-
- if (process.exitValue() == 0) {
- return new String(process.getInputStream().readAllBytes());
- } else {
- String errorOutput = new String(process.getErrorStream().readAllBytes());
- throw new IOException(ErrorMessage.EXECUTION_FAILED.getMessage() + "\n" + errorOutput);
- }
- }
-
- private String generateFileName(String language) {
- return UUID.randomUUID() + getExtension(language);
- }
-
- private String getExtension(String language) {
- //TODO ENUM
- return switch (language.toLowerCase()) {
- case "c" -> ".c";
- case "java" -> ".java";
- case "python" -> ".py";
- default -> throw new IllegalArgumentException(ErrorMessage.UNSUPPORTED_LANGUAGE.getMessage());
- };
+ return result;
}
}
\ No newline at end of file | Java | ํด๋์ค๊ฐ ๋๋ฌด ํฝ๋๋ค. ์ญํ ์ ๋๋ ์ฃผ์ธ์ |
@@ -1,36 +1,40 @@
package com.example.project.compile.controller.rest;
+import com.example.project.auth.service.AuthTokenService;
import com.example.project.common.dto.ResponseDto;
import com.example.project.common.dto.ResponseMessage;
-import com.example.project.solution.dto.request.user.SolutionCompileRequest;
+import com.example.project.common.util.HeaderUtil;
+import com.example.project.compile.dto.CompileRequest;
import com.example.project.compile.service.CompileService;
+import com.example.project.error.dto.ErrorMessage;
+import com.example.project.error.dto.ErrorResponseDto;
+import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
-import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
+@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/compile")
public class CompileApiController {
+
private final CompileService compileService;
+ private final AuthTokenService authTokenService;
@PostMapping
- @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
- public ResponseEntity<?> compileCode(@RequestBody SolutionCompileRequest request) {
- try {
- String result = compileService.compileAndRun(request.getLanguage(), request.getCode());
+ public ResponseEntity<?> compileCode(@RequestBody CompileRequest request, HttpServletRequest httpServletRequest, @Value("${compile.url}") String codeDir) throws IOException {
+ if (authTokenService.isValidateToken(HeaderUtil.resolveToken(httpServletRequest))) {
+ String result = compileService.compileAndRun(
+ request.getLanguage(),
+ request.getCode(),
+ codeDir
+ );
return ResponseDto.toResponseEntity(ResponseMessage.COMPILE_SUCCESS, result);
- } catch (IllegalArgumentException e) {
- return ResponseDto.toResponseEntity(ResponseMessage.INVALID_LANGUAGE, e.getMessage());
- } catch (IOException e) {
- return ResponseDto.toResponseEntity(ResponseMessage.IO_ERROR, e.getMessage());
- } catch (InterruptedException e) {
- return ResponseDto.toResponseEntity(ResponseMessage.EXECUTION_INTERRUPTED, e.getMessage());
- } catch (Exception e) {
- return ResponseDto.toResponseEntity(ResponseMessage.GENERAL_COMPILE_ERROR, e.getMessage());
- }
+ } else return ErrorResponseDto.of(ErrorMessage.NOT_FOUND_CLIENT_ID_HEADER);
}
}
\ No newline at end of file | Java | HttpServletRequest๋ง ๋ฐ์์ค๋ฉด ํ ํฐ ๊ฐ์ ๋ฐ๋ก ๋ฐ์์ค์ง ์์๋ ๋ฉ๋๋ค |
@@ -0,0 +1,37 @@
+package com.example.project.compile.service;
+
+import com.example.project.compile.domain.CompileLanguage;
+import com.example.project.error.dto.ErrorMessage;
+import org.springframework.stereotype.Service;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.InvalidPathException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.UUID;
+
+@Service
+public class FileService {
+
+ public Path createCodeFile(String code, CompileLanguage compileLanguage, String codeDir) throws IOException {
+ try {
+ Path codePath = Paths.get(codeDir);
+ if (!Files.exists(codePath)) {
+ Files.createDirectories(codePath);
+ }
+
+ //UUID๋ฅผ ์ฌ์ฉํ๋ ์ด์ ๋ ๊ณ ์ ํ ํ์ผ ์ด๋ฆ์ ์์ฑํ์ฌ ํ์ผ์ ์ถฉ๋์ ๋ฐฉ์งํ๊ธฐ ์ํจ์
๋๋ค.
+ String filename = "Main_" + UUID.randomUUID() + compileLanguage.getExtension();
+
+ Path filePath = codePath.resolve(filename);
+ Files.writeString(filePath, code);
+ return filePath;
+
+ } catch (InvalidPathException e) {
+ throw new IOException(ErrorMessage.INVALID_PATH_EXCEPTION.getMessage(), e);
+ } catch (SecurityException e) {
+ throw new IOException(ErrorMessage.ACCESS_PERMISSION_EXCEPTION.getMessage(), e);
+ }
+ }
+}
\ No newline at end of file | Java | yml ์ ์ค์ ํ ๊ฐ์ ์ฌ์ฉํด์ฃผ์ธ์.
๊ทธ๋ฆฌ๊ณ static์ ์ฌ์ฉํ ํ์๋ ์์ด๋ณด์
๋๋ค. |
@@ -1,36 +1,40 @@
package com.example.project.compile.controller.rest;
+import com.example.project.auth.service.AuthTokenService;
import com.example.project.common.dto.ResponseDto;
import com.example.project.common.dto.ResponseMessage;
-import com.example.project.solution.dto.request.user.SolutionCompileRequest;
+import com.example.project.common.util.HeaderUtil;
+import com.example.project.compile.dto.CompileRequest;
import com.example.project.compile.service.CompileService;
+import com.example.project.error.dto.ErrorMessage;
+import com.example.project.error.dto.ErrorResponseDto;
+import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
-import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
+@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/compile")
public class CompileApiController {
+
private final CompileService compileService;
+ private final AuthTokenService authTokenService;
@PostMapping
- @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
- public ResponseEntity<?> compileCode(@RequestBody SolutionCompileRequest request) {
- try {
- String result = compileService.compileAndRun(request.getLanguage(), request.getCode());
+ public ResponseEntity<?> compileCode(@RequestBody CompileRequest request, HttpServletRequest httpServletRequest, @Value("${compile.url}") String codeDir) throws IOException {
+ if (authTokenService.isValidateToken(HeaderUtil.resolveToken(httpServletRequest))) {
+ String result = compileService.compileAndRun(
+ request.getLanguage(),
+ request.getCode(),
+ codeDir
+ );
return ResponseDto.toResponseEntity(ResponseMessage.COMPILE_SUCCESS, result);
- } catch (IllegalArgumentException e) {
- return ResponseDto.toResponseEntity(ResponseMessage.INVALID_LANGUAGE, e.getMessage());
- } catch (IOException e) {
- return ResponseDto.toResponseEntity(ResponseMessage.IO_ERROR, e.getMessage());
- } catch (InterruptedException e) {
- return ResponseDto.toResponseEntity(ResponseMessage.EXECUTION_INTERRUPTED, e.getMessage());
- } catch (Exception e) {
- return ResponseDto.toResponseEntity(ResponseMessage.GENERAL_COMPILE_ERROR, e.getMessage());
- }
+ } else return ErrorResponseDto.of(ErrorMessage.NOT_FOUND_CLIENT_ID_HEADER);
}
}
\ No newline at end of file | Java | ์ปดํ์ผํ๋ ์๋ฒ์์๋ JWT ํ ํฐ์ ๊ฐ์ง๊ณ ์ ํจํ ์ ๊ทผ์ธ์ง ์๋์ง ํ๋จํด์ ์ปดํ์ผํ ์ ์๋๋ก ํด์ฃผ์ธ์ |
@@ -0,0 +1,37 @@
+package com.example.project.compile.service;
+
+import com.example.project.compile.domain.CompileLanguage;
+import com.example.project.error.dto.ErrorMessage;
+import org.springframework.stereotype.Service;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.InvalidPathException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.UUID;
+
+@Service
+public class FileService {
+
+ public Path createCodeFile(String code, CompileLanguage compileLanguage, String codeDir) throws IOException {
+ try {
+ Path codePath = Paths.get(codeDir);
+ if (!Files.exists(codePath)) {
+ Files.createDirectories(codePath);
+ }
+
+ //UUID๋ฅผ ์ฌ์ฉํ๋ ์ด์ ๋ ๊ณ ์ ํ ํ์ผ ์ด๋ฆ์ ์์ฑํ์ฌ ํ์ผ์ ์ถฉ๋์ ๋ฐฉ์งํ๊ธฐ ์ํจ์
๋๋ค.
+ String filename = "Main_" + UUID.randomUUID() + compileLanguage.getExtension();
+
+ Path filePath = codePath.resolve(filename);
+ Files.writeString(filePath, code);
+ return filePath;
+
+ } catch (InvalidPathException e) {
+ throw new IOException(ErrorMessage.INVALID_PATH_EXCEPTION.getMessage(), e);
+ } catch (SecurityException e) {
+ throw new IOException(ErrorMessage.ACCESS_PERMISSION_EXCEPTION.getMessage(), e);
+ }
+ }
+}
\ No newline at end of file | Java | ๋ณ์๋ช
์ ์นด๋ฉ์ผ์ด์ค๋ฅผ ์ง์ผ์ ์์ฑํด์ฃผ์ธ์ |
@@ -0,0 +1,54 @@
+const generateBasicToken = (userId: string, userPassword: string): string => {
+ const token = btoa(`${userId}:${userPassword}`);
+ return `Basic ${token}`;
+};
+
+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}`;
+
+try {
+ if (!API_URL || !USER_ID || !USER_PASSWORD) {
+ throw new Error(
+ "API_URL, USER_ID, PASSWORD environment variables are not set",
+ );
+ }
+} catch (error) {
+ console.log(error);
+}
+
+type HttpMethod = "GET" | "POST" | "PATCH" | "DELETE";
+
+interface RequestOptions {
+ method: HttpMethod;
+ body?: Record<string, unknown>;
+}
+
+export const fetchWithAuth = async (path: string, options: RequestOptions) => {
+ const requestInit = requestBuilder(options);
+ const response = await fetch(path, requestInit);
+
+ try {
+ if (!response.ok) {
+ throw new Error(`Failed to ${options.method} ${path}`);
+ }
+ } catch (error) {
+ console.log(error);
+ }
+
+ return response;
+};
+
+const requestBuilder = ({ method, body }: RequestOptions): RequestInit => {
+ const token = generateBasicToken(USER_ID, USER_PASSWORD);
+ const headers: HeadersInit = {
+ "Content-Type": "application/json",
+ Authorization: token,
+ };
+
+ return {
+ method,
+ headers,
+ body: body ? JSON.stringify(body) : undefined,
+ };
+}; | TypeScript | ```
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}`;
```
์ด ๋ถ๋ถ์ ์์ ํ์ผ์์ ๋ฐ๋ก ๊ด๋ฆฌํด๋ณด๋ ๊ฒ์ ์ด๋จ๊น์?
`API_URL `์ด ์์ด๋ endPoint, fetchWithAuth์์ ๋ ๋ฒ ์ ์ธ๋๋ค์ |
@@ -0,0 +1,123 @@
+import { RULE } from "@constants/rules";
+import {
+ CART_ITEMS_COUNTS_ENDPOINT,
+ CART_ITEMS_ENDPOINT,
+ PRODUCTS_ENDPOINT,
+} from "./endpoints";
+import { fetchWithAuth } from "./fetchWithAuth";
+
+/**
+ * @example
+ * const params: QueryParams = {
+ * category: 'fashion',
+ * page: 1,
+ * size: 20,
+ * sort: ['price', 'asc']
+ * }
+ */
+interface QueryParams {
+ [key: string]:
+ | undefined
+ | string
+ | number
+ | boolean
+ | (string | number | boolean)[];
+}
+
+export interface GetProductsParams {
+ category?: Category;
+ page?: number;
+ size?: number;
+ sort?: Sort;
+}
+
+const createQueryString = (params: QueryParams) => {
+ return Object.entries(params)
+ .filter(([, value]) => value !== undefined)
+ .map(([key, value]) => {
+ if (Array.isArray(value)) {
+ return `${encodeURIComponent(key)}=${encodeURIComponent(value.join(","))}`;
+ }
+ return `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`;
+ })
+ .join("&");
+};
+
+export const getProducts = async ({
+ category,
+ page = 0,
+ size = 20,
+ sort = "asc",
+}: GetProductsParams = {}): Promise<Product[]> => {
+ const params = {
+ category,
+ page,
+ size,
+ sort: ["price", sort],
+ };
+ const queryString = createQueryString(params) + RULE.sortQueryByIdAsc;
+
+ const response = await fetchWithAuth(`${PRODUCTS_ENDPOINT}?${queryString}`, {
+ method: "GET",
+ });
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error("Failed to get products item");
+ }
+
+ return data.content;
+};
+
+export const postProductInCart = async (
+ productId: number,
+ quantity: number = 1,
+) => {
+ const response = await fetchWithAuth(CART_ITEMS_ENDPOINT, {
+ method: "POST",
+ body: {
+ productId,
+ quantity,
+ },
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to post product item in cart");
+ }
+};
+
+export const deleteProductInCart = async (cartId: number) => {
+ const response = await fetchWithAuth(`${CART_ITEMS_ENDPOINT}/${cartId}`, {
+ method: "DELETE",
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to delete product item in cart");
+ }
+};
+
+export const getCartItemsCount = async (): Promise<number> => {
+ const response = await fetchWithAuth(CART_ITEMS_COUNTS_ENDPOINT, {
+ method: "GET",
+ });
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error("Failed to get cart items count");
+ }
+
+ return data;
+};
+
+export const getCartItems = async (): Promise<CartItem[]> => {
+ const response = await fetchWithAuth(CART_ITEMS_ENDPOINT, {
+ method: "GET",
+ });
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error("Failed to get cart items count");
+ }
+
+ return data.content;
+}; | TypeScript | ์์ฒญํด์ผํ๋ api ๊ฐ ๋ง์์ง๋ค๋ฉด, api/index.ts ์ฝ๋๊ฐ ๋ง์์ง๊ฒ ๋ค์.
๊ด๋ จ์๋ api ์์ฒญ ๋ผ๋ฆฌ ๋ฌถ์ด์ ํ์ผ๋ก ๊ด๋ฆฌํ๊ณ , index.ts์์ ํด๋น ํ์ผ๋ค์ api ์์ฒญ ๋ฉ์๋๋ฅผ export ํ๋ ๊ฒ์ ์ด๋จ๊น์?
```dash
api
ใด cart
ใด products
ใด index
``` |
@@ -0,0 +1,61 @@
+import { forwardRef, useContext } from "react";
+import * as PI from "./ProductItem.style";
+import CartControlButton from "../../Button/CartControlButton";
+import { deleteProductInCart, postProductInCart } from "@api/index";
+import { useError } from "@hooks/index";
+import { CartItemsContext } from "@context/CartItemsContext";
+
+interface ProductProps {
+ product: Product;
+}
+
+const ProductItem = forwardRef<HTMLDivElement, ProductProps>(
+ ({ product }, ref) => {
+ const { cartItems, refreshCartItems } = useContext(CartItemsContext);
+
+ const cartItemIds = cartItems.map((item) => item.product.id);
+ const isInCart = cartItemIds.includes(product.id);
+
+ const { showError } = useError();
+
+ const handleIsInCart = async () => {
+ try {
+ if (!isInCart) {
+ await postProductInCart(product.id);
+ refreshCartItems();
+ return;
+ }
+
+ const filteredItem = cartItems.find(
+ (item) => item.product.id === product.id,
+ );
+ if (filteredItem) {
+ await deleteProductInCart(filteredItem.id);
+ refreshCartItems();
+ }
+ } catch (error) {
+ if (error instanceof Error) {
+ showError(error.message);
+ }
+ }
+ };
+
+ return (
+ <PI.ProductItemStyle ref={ref}>
+ <PI.ProductImg
+ src={`${product.imageUrl}`}
+ alt={`${product.name} ์ํ ์ด๋ฏธ์ง`}
+ />
+ <PI.ProductGroup>
+ <PI.ProductContent>
+ <PI.ProductName>{product.name}</PI.ProductName>
+ <span>{product.price.toLocaleString("ko-kr")}์</span>
+ </PI.ProductContent>
+ <CartControlButton onClick={handleIsInCart} isInCart={isInCart} />
+ </PI.ProductGroup>
+ </PI.ProductItemStyle>
+ );
+ },
+);
+
+export default ProductItem; | Unknown | ์ฅ๋ฐ๊ตฌ๋์ ๋ด๋ ๋ก์ง๊ณผ ๋นผ๋ ๋ก์ง์ ํจ์๋ก ๋ถ๋ฆฌํ๊ณ ,
if else๋์ early return ์ ์ฌ์ฉํด๋ณด๋ ๊ฒ์ ์ด๋จ๊น์? |
@@ -0,0 +1,61 @@
+import { forwardRef, useContext } from "react";
+import * as PI from "./ProductItem.style";
+import CartControlButton from "../../Button/CartControlButton";
+import { deleteProductInCart, postProductInCart } from "@api/index";
+import { useError } from "@hooks/index";
+import { CartItemsContext } from "@context/CartItemsContext";
+
+interface ProductProps {
+ product: Product;
+}
+
+const ProductItem = forwardRef<HTMLDivElement, ProductProps>(
+ ({ product }, ref) => {
+ const { cartItems, refreshCartItems } = useContext(CartItemsContext);
+
+ const cartItemIds = cartItems.map((item) => item.product.id);
+ const isInCart = cartItemIds.includes(product.id);
+
+ const { showError } = useError();
+
+ const handleIsInCart = async () => {
+ try {
+ if (!isInCart) {
+ await postProductInCart(product.id);
+ refreshCartItems();
+ return;
+ }
+
+ const filteredItem = cartItems.find(
+ (item) => item.product.id === product.id,
+ );
+ if (filteredItem) {
+ await deleteProductInCart(filteredItem.id);
+ refreshCartItems();
+ }
+ } catch (error) {
+ if (error instanceof Error) {
+ showError(error.message);
+ }
+ }
+ };
+
+ return (
+ <PI.ProductItemStyle ref={ref}>
+ <PI.ProductImg
+ src={`${product.imageUrl}`}
+ alt={`${product.name} ์ํ ์ด๋ฏธ์ง`}
+ />
+ <PI.ProductGroup>
+ <PI.ProductContent>
+ <PI.ProductName>{product.name}</PI.ProductName>
+ <span>{product.price.toLocaleString("ko-kr")}์</span>
+ </PI.ProductContent>
+ <CartControlButton onClick={handleIsInCart} isInCart={isInCart} />
+ </PI.ProductGroup>
+ </PI.ProductItemStyle>
+ );
+ },
+);
+
+export default ProductItem; | Unknown | alt์ ๋ํด์ ์ ๋ฒ ๋ฏธ์
์์ ํ๋ฃจ์๊ฒ ๋ฐ์ ํผ๋๋ฐฑ์ ๊ณต์ ํ ๊ฒ์.
image์ alt๋ 'ํฐ ์ด๋ํ์ ๊ฒ์์ ์ค์ด ํ๋ ๋ค์ด๊ฐ ์๋๋ค์ค ์ด๋ํ'์ฒ๋ผ ํด๋น ์ด๋ฏธ์ง์ ๋ํ ๊ตฌ์ฒด์ ์ธ ์ค๋ช
์ด ๋ค์ด๊ฐ์ผํด์.
ํ์ง๋ง ํ์ฌ ์๋ฒ์์ ์ฃผ๋ ์์ธํ ์ํ ์ค๋ช
์ด ์๋ ์ํฉ์์๋`alt=''"`๋ฅผ ์ฌ์ฉํ๋ ๊ฒ์ด ์ข๋ค๊ณ ํ๋ค์.
alt๋ฅผ ์ฌ์ฉํ์ง ์๋ ๊ฒ๊ณผ alt์ ๋น๋ฌธ์์ด๋ก ๋๋ ๊ฒ์ ์ฐจ์ด๋ฅผ ๊ณต๋ถํด๋ณธ๋ค๋ฉด, ์ํ์๊ฒ ๋์์ด ๋ ๊ฑฐ์์. ๐ |
@@ -0,0 +1,44 @@
+import { FILTER_CATEGORIES, SORT_PRICE } from "@constants/rules";
+import * as PLH from "./ProductListHeader.style";
+
+interface ProductListHeaderProps {
+ handleCategory: (category: Category) => void;
+ handleSort: (sort: Sort) => void;
+}
+
+const ProductListHeader = ({
+ handleCategory,
+ handleSort,
+}: ProductListHeaderProps) => {
+ return (
+ <PLH.Header>
+ <PLH.Title>bpple ์ํ ๋ชฉ๋ก</PLH.Title>
+ <PLH.SelectBoxGroup>
+ <PLH.SelectBox
+ name=""
+ id=""
+ onChange={(e) => handleCategory(e.target.value as Category)}
+ >
+ {Object.entries(FILTER_CATEGORIES).map(([key, value]) => (
+ <option value={key} key={key}>
+ {value}
+ </option>
+ ))}
+ </PLH.SelectBox>
+ <PLH.SelectBox
+ name=""
+ id=""
+ onChange={(e) => handleSort(e.target.value as Sort)}
+ >
+ {Object.entries(SORT_PRICE).map(([key, value]) => (
+ <option value={key} key={key}>
+ {value}
+ </option>
+ ))}
+ </PLH.SelectBox>
+ </PLH.SelectBoxGroup>
+ </PLH.Header>
+ );
+};
+
+export default ProductListHeader; | Unknown | selectbox ๋ ๋ค name,id๋ฅผ ๋น๋ฌธ์์ด๋ก ๋ ์ด์ ๊ฐ ์์๊น์? |
@@ -0,0 +1,44 @@
+import { FILTER_CATEGORIES, SORT_PRICE } from "@constants/rules";
+import * as PLH from "./ProductListHeader.style";
+
+interface ProductListHeaderProps {
+ handleCategory: (category: Category) => void;
+ handleSort: (sort: Sort) => void;
+}
+
+const ProductListHeader = ({
+ handleCategory,
+ handleSort,
+}: ProductListHeaderProps) => {
+ return (
+ <PLH.Header>
+ <PLH.Title>bpple ์ํ ๋ชฉ๋ก</PLH.Title>
+ <PLH.SelectBoxGroup>
+ <PLH.SelectBox
+ name=""
+ id=""
+ onChange={(e) => handleCategory(e.target.value as Category)}
+ >
+ {Object.entries(FILTER_CATEGORIES).map(([key, value]) => (
+ <option value={key} key={key}>
+ {value}
+ </option>
+ ))}
+ </PLH.SelectBox>
+ <PLH.SelectBox
+ name=""
+ id=""
+ onChange={(e) => handleSort(e.target.value as Sort)}
+ >
+ {Object.entries(SORT_PRICE).map(([key, value]) => (
+ <option value={key} key={key}>
+ {value}
+ </option>
+ ))}
+ </PLH.SelectBox>
+ </PLH.SelectBoxGroup>
+ </PLH.Header>
+ );
+};
+
+export default ProductListHeader; | Unknown | selectbox๋ฅผ ํ๋์ ์ปดํฌ๋ํธ๋ก ๋ถ๋ฆฌํด๋ ์ข์ ๊ฒ ๊ฐ์์. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.