Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
06ecdde
initial commit
BoRamSon Nov 23, 2024
6a0644b
docs(README): 구현할 기능 목록 생성
BoRamSon Nov 23, 2024
bc1f8a3
# npm audit report
BoRamSon Nov 23, 2024
63b47f4
docs(README): 구현할 기능 목록 수정
BoRamSon Nov 23, 2024
fca6709
feat(InputView): 경주할 자동차 이름을 입력 받는다.
BoRamSon Nov 23, 2024
cef977c
feat(constants): add errorMessages for validation
BoRamSon Nov 23, 2024
36fecba
feat(validation): 입력받은 자동차 이름값을 검증하는 각각의 함수 생성
BoRamSon Nov 23, 2024
c5b77a3
feat(validation): 입력받은 자동차 이름값들을 검증하는 함수
BoRamSon Nov 23, 2024
38c680e
feat(util): string type의 입력값을 (,)를 기준으로 array로 만드는 도구 함수 생성
BoRamSon Nov 23, 2024
3c6a46b
fix(validation): import에 파일명 .js 추가
BoRamSon Nov 23, 2024
b841c71
feat(controller): 입력받은 자동차 이름값들을 검증한다.
BoRamSon Nov 23, 2024
f83dff3
feat(InputView): 시도할 횟수를 입력받는다.
BoRamSon Nov 23, 2024
df51072
feat(constants): add errorMessage for number of try
BoRamSon Nov 23, 2024
1c9cd30
docs(README): 구현할 기능 목록 수정
BoRamSon Nov 23, 2024
302f494
feat(validation): 과도한 시도횟수를 방지하는 함수 생성
BoRamSon Nov 23, 2024
c7fd9e5
chore: 매개변수 이름 수정
BoRamSon Nov 23, 2024
4ddb838
feat(validation): 시도횟수를 검증하는 validation 함수 생성
BoRamSon Nov 23, 2024
c3b8cd6
feat(controller): 입력받은 시도할 홧수를 검증한다.
BoRamSon Nov 23, 2024
30e255d
feat(controller): 0에서 9 사이에서 무작위 값을 구하는 메서드 생성
BoRamSon Nov 23, 2024
2c93fd0
chore(controller): carName을 입력받고 검증하는 로직을 racing 메서드에서 빼서 별도의 메서드로 만들기
BoRamSon Nov 23, 2024
0bb40ae
chore(controller): tryNumber을 입력받고 검증하는 로직을 racing 메서드에서 빼서 별도의 메서드로 만들기
BoRamSon Nov 23, 2024
8807125
fix(controller): validationTryNumber() 메서드에서 필요없는 코드 제거 및 Number() 타입…
BoRamSon Nov 23, 2024
1aaefa5
fix(controller): await 코드 누락으로 추가
BoRamSon Nov 23, 2024
7e32df4
chore(util): 파일 이름 오타로 인하여 파일이름 변경
BoRamSon Nov 23, 2024
104dc60
feat(util): array를 객체배열로 만들 수 있는 도구를 생성
BoRamSon Nov 23, 2024
81dc21e
feat(controller): 기존에 array 형태로 존재했던 carName을 객체배열로 받을 수 있도록 makeObje…
BoRamSon Nov 23, 2024
6b7336b
chore(util): 객체배열 명칭 오타로 인하여 수정
BoRamSon Nov 23, 2024
9c50bc7
feat(controller): 전진하는 조건은 무작위 값이 4 이상일 경우이다. 이 조건으로 게임을 시작한다.
BoRamSon Nov 23, 2024
1959b1f
feat(controller): 게임진행상황이 출력될 수 있도록 구현
BoRamSon Nov 23, 2024
0dcbc5f
feat(controller): 우승자 출력하기까지 구현 완료
BoRamSon Nov 23, 2024
be1773b
fix(validation): import 경로 변경, forEach 코드 변경
BoRamSon Nov 23, 2024
0d7efed
chore(controller): 주석 제거
BoRamSon Nov 23, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1 +1,69 @@
# javascript-racingcar-precourse

 
## 초간단 자동차 경주 게임을 구현한다.

 
### ● 경주할 자동차 이름을 쉼표(,)기준으로 구분하여 각각 5자 이하로만 입력받는다.
경주할 자동차 이름을 입력하세요. (이름은 쉼표(,) 기준으로 구분) \n =>


 
### ● 입력받은 자동차 이름값들을 검증한다.
- 빈값 여부
- 에러 여부
- 쉼표 구분여부
- 영어입력 여부
- 5자이하 여부


 
### ● 검증 중 입력값에 문제가 있을 경우, 완전히 종료된다.
사용자가 잘못된 값을 입력할 경우 "[ERROR]"로 시작하는 메시지와 함께 Error를 발생시킨 후 애플리케이션은 종료되어야 한다.


 
### ● 시도할 횟수를 입력받는다.
시도할 횟수는 몇 회인가요? \n =>

 
### ● 입력받은 시도할 홧수를 검증한다.
- 빈값 여부
- 숫자가 입력되었는지 여부
- 과도한 시도 횟수 방지 (임의 20 제한)


 
### ● 검증 중 입력값에 문제가 있을 경우, 완전히 종료된다.
사용자가 잘못된 값을 입력할 경우 "[ERROR]"로 시작하는 메시지와 함께 Error를 발생시킨 후 애플리케이션은 종료되어야 한다.

 
### ● 입력받은 값들에 문제가 없으면 게임이 시작된다.


 
### ● 게임 진행 규칙
주어진 횟수 동안 n대의 자동차는 전진 또는 멈출 수 있다.
전진하는 조건은 0에서 9 사이에서 무작위 값을 구한 후 무작위 값이 4 이상일 경우이다.


 
### ● 게임 진행 상황을 출력할 때 자동차 이름을 같이 출력한다.
<출력 예시>
pobi : --
woni :
jun : -


&nbsp;
### ● 우승자 출력하기
입력된 시도횟수만큼 게임 진행 후 가장 멀리 간 자동차가 우승이다.
자동차 경주 게임을 완료한 후 누가 우승했는지를 출력하여 알려준다.
<출력 예시>
최종 우승자 : pobi

전진한 횟수가 동점인 경우 우승자는 한 명 이상일 수 있다.
우승자가 여러 명일 경우 쉼표(,)를 이용하여 구분한다.
<출력 예시>
최종 우승자 : pobi, jun

6 changes: 3 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 9 additions & 1 deletion src/App.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import RacingController from "./controller/RacingController.js";

class App {
async run() {}
constructor () {
this.racingController = new RacingController
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오 여기 RaceController뒤에 ()가 빠진것 같은데, 정상적으로 동작하는지 궁금하군요...? 👀

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저도 이부분 궁금하네용

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저도 궁금합니다!!

Copy link
Owner Author

@BoRamSon BoRamSon Nov 27, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

정확한 원리는 잘 모르겠지만, 이 부분 제가 직접 해봤었는데 괄호가 없어도 작동이 됐었습니다!
아마도 괄호에 매개변수나 들어갈게 없다보니 되지 않았을까? 추측합니다.
기본적인 prettier만 적용해도 자동고침(괄호적용) 되는 부분입니다.


async run() {
this.racingController.racing();
}
}

export default App;
8 changes: 8 additions & 0 deletions src/constants/errorMessages.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const ERROR_MESSAGES = {
VALIDATE_EMPTY: "[ERROR] 입력값이 없습니다. 다시 입력해주세요.",
VALIDATE_NOT_CORRECT_REGEX: "[ERROR] 형식이 올바르지 않습니다.",
VALIDATE_FIVE_LENGTH: "[ERROR] 입력된 자동차 이름 중에서 5글자가 넘는 이름이 존재합니다.",
VALIDATE_LIMIT_NUMBER: "[ERROR] 너무 과도한 시도 횟수를 입력하셨습니다.",
Comment on lines +2 to +5

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

지인님께도 드렸던 피드백인데
ERROR_PREFIX와 텍스트를 인자로 에러 텍스트를 생성하는 로직을 재사용하는 방법도 있으니 참고하면 좋을 것 같아요!

ex)

const createMsg = (msg) => `${ERROR_PREFIX} ${msg}\n`;

};

export default ERROR_MESSAGES;
Comment on lines +1 to +8

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

'[ERROR]' 문자가 반복되니 이 부분도 상수처리로 하면 어떨까요~?
예를 들어 ERROR_PREFIX: '[ERROR]' 로 하였을 때 개인적으로는 가독성이 좋아지더라고요!

104 changes: 104 additions & 0 deletions src/controller/RacingController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { MissionUtils } from "@woowacourse/mission-utils";
import validateCarNames from "../validation/validateCarNames.js";
import validateTryNumber from "../validation/validateTryNumber.js";
import makeArrayFromString from "../utils/makeArrayFromString.js";
import makeObjectFromArray from "../utils/makeObjectFromArray.js";

class RacingController {
async racing() {
const carNamesObject = await this.getCarNamesObject();
const tryNumber = await this.getTryNumber();
const carRacingResult = this.startCarRacing(carNamesObject, tryNumber);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tryNumber네이밍이 경기 횟수 입력한 부분을 의미하는 것 같은데, 명확하지 않은 것 같아요~!
경기횟수라는 의미가 들어가는 네이밍으로 작성하시면 더 좋을 것 같습니다!

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

엇 저같은 경우는 레이싱을 시도하는 횟수라고 생각해서 tryCount라는 네이밍을 사용한 기억이 있네요 ,,, ㅋㅋㅋㅋ

this.printWinner(carRacingResult);
return;
}

async getCarNamesObject() {
const carNames = await this.readCarNames();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

개인적으로 고민이 되는 부분은,
입력 받은 값을 함수로 네이밍을 지을 때
read / get ~ input 중에서 어떤게 더 직관적인지 고민이 되더라고요 ㅎㅎ
보람님 생각도 궁금합니다 :) !!

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

참고로 저는 get ~ input을 템플릿 처럼 쓰고 있는데, 이게 글자수도 길어져서 read 로 작성할지..? 고민이 되어요 ㅎㅎ

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

잘 모르는 상태로 보통 뒤죽박죽 써왔지만,
지금까지의 저의 생각은요.
사용자로부터 뭔가 입력을 받을 때에는 input을 쓰려고 생각했었구요.
무언가 데이터를 가공해서 얻어내는 것은 get을 썼었습니다.
(원래 read는 잘 사용하지 않았다가 여러 메서드나 함수가 많아지면서 네이밍이 비슷해지는 것을 막기 위해서 read가 나왔던 것 같습니다.)

const stringType = String(carNames);
const validatedCarNames = this.validationCarNames(stringType);
const carNamesArray = makeArrayFromString(validatedCarNames);
MissionUtils.Console.print("");

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

import할 때, Console 자체를 import를 하면 어떨까요~?
그렇게 하면 매번 Console.print 앞에 MissionUtils. 적을 필요가 없으니 더 간결해 보일 것 같아요~!

Copy link
Owner Author

@BoRamSon BoRamSon Nov 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

편의점 과제 구현할 때에 throw new Error() 로 종료시키지 않고 에러를 보내서 테스트 코드를 통과하려고 Console.print();로 해서 통과가 안되었는데, 다른 방법을 찾아보다가 MissionUtils.Console.print();로 테스트 통과가 되어서 다른 것으로 알고 있었습니다.
무슨 차이인지는 좀 더 알아보겠습니다.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오호... 저도 항상 Console을 import해서 사용하던 터라 무슨 차이인지 궁금하네요 👀

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@BoRamSon 그렇군요! 어떤 부분이 문제였는지 궁금합니다 :)
저도 @rosielsh 주화님 처럼 항상 Console을 import했었는데, 혹시 다른 부분이 문제는 아니었을지? 궁금하네요!!

Copy link
Owner Author

@BoRamSon BoRamSon Nov 27, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

편의점 구현 때 무조건 테스트코드를 먼저 통과시키려고 노력할 때였습니다.
throw를 쓰면 로직이 끝나버리고, try{}catch{}도 안쓰고 무조건 테스트 조건에 맞추려고 하다가 Console.log, Console.print, 사용했는데 테스트통과가 안되다가 MissionUtils.Console.print 사용하고 테스트 통과가 되었던 적이 있었습니다.

if (item.quantity > product.quantity) {
     // throw new Error(
          //   "[ERROR] 재고 수량을 초과하여 구매할 수 없습니다. 다시 입력해 주세요."
     // );
    MissionUtils.Console.print(
       '[ERROR] 재고 수량을 초과하여 구매할 수 없습니다. 다시 입력해 주세요.'
    );
}

원리는 어떻게 알아내야할지 잘 모르겠습니다 ㅠ

테스트 코드 찾아보니 아래와 같이 되어있기는 한데요.

test("예외 테스트", async () => {
    await runExceptions({
      inputs: ["[컵라면-12]", "N", "N"],
      inputsToTerminate: INPUTS_TO_TERMINATE,
      expectedErrorMessage:
        "[ERROR] 재고 수량을 초과하여 구매할 수 없습니다. 다시 입력해 주세요.",
    });
  });

npm package module을 뜯어보는 방법이나 어떤 역할을 하는지 확인해보는 방법을 열심히 찾아봤는데요.

https://github.com/woowacourse-projects/javascript-mission-utils/blob/main/src/index.js
package 출처에서 확인해본 결과
MissionUtils.Console.print과 Console.print가 하는 역할에는 전혀 차이가 없는 것을 확인했습니다.


제가 테스트코드를 모르지만, 편의점 테스트코드를 다시 확인해보니 MissionUtils만 import가 되어있어서 MissionUtils.Console.print로 출력되는 것만 인식했던 것이 아닐까? 추측해봅니다...

import { MissionUtils } from "@woowacourse/mission-utils";

결론적으로 문제가 없으셨다면, 역할에 전혀 차이가 없어보이니 간결하게 Console.print로 쓰면 될 것 같습니다!

return makeObjectFromArray(carNamesArray);
}

async getTryNumber() {
const tryNumber = await this.readTryNumbers();
const validtedTryNumber = this.validationTryNumber(tryNumber);
MissionUtils.Console.print("");
return Number(validtedTryNumber);
}

async readCarNames() {
const inputCarNames = await MissionUtils.Console.readLineAsync(
"경주할 자동차 이름을 입력하세요. (이름은 쉼표(,) 기준으로 구분) \n => "
Comment on lines +33 to +34

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

에러 메시지를 상수화 한 것 처럼, input 메시지도 상수처리해서 관리하면 어떨까요~? 유지보수 측면에서 더 좋을 것 같아서 피드백 드립니다 :) !!

);
const stringType = String(inputCarNames);
const removeSpace = stringType.replace(/ /g, "");
return removeSpace;
Comment on lines +36 to +38

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

stringType, removeSpace라는 네이밍보다 조금 더 변수의 의미를 드러내는 stringCar, removeSpaceCar이라는 네이밍은 어떨까요?

}

validationCarNames(validationTarget) {
validateCarNames(validationTarget);
return validationTarget;
}

async readTryNumbers() {
const inputCarNames = await MissionUtils.Console.readLineAsync(
"시도할 횟수는 몇 회인가요? \n => "
);
const removeSpace = inputCarNames.replace(/ /g, "");

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

문자열의 양 옆의 공백을 제거하는 용이라면 trim 메서드를 활용해도 좋을 거 같아요!

return removeSpace;
}

validationTryNumber(validationTarget) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

validateTryNumber 함수를 바로 사용해도 되는 상황처럼 보이는데 클래스 내부 메서드로 한번 더 감싼 이유가 있을까요??

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

네 validation 함수로 만들어놓았고, 그냥 그대로 가져다 쓰기만 하면되는데, 제가 왜 메서드로 한번 더 감싸게 되었는지 모르겠네요.. 별 이유가 있는 것은 아니였습니다 ㅎ

validateTryNumber(validationTarget);
return validationTarget;
}

getRandomNumber() {
return MissionUtils.Random.pickNumberInRange(0, 9);
}

changeDashUtil(number) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

number보다는 진행 정도를 나타내게끔 forwardCount 같은 변수도 좋을 거 같아요!

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

네이밍에 조금 더 신경을 써야겠습니다 ㅎ

let dash = "";
for (let i = 0; i < number; i++) {
dash += "-";
}
return dash;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

자바스크립트 repeat 메서드를 활용해도 좋을 거 같아요!

return '-'.repeat(number);

}

printGameProgress(object) {
object.map((array) => {
const carName = array.name;
const dash = this.changeDashUtil(array.forward);
return MissionUtils.Console.print(`${carName} : ${dash}`);
});
MissionUtils.Console.print("");
}
Comment on lines +71 to +78
Copy link

@xxziiko xxziiko Nov 25, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

매개변수명을 object라고 하신 특별한 이유가 있으실까요? 배열을 map 하는 것 같은데 네이밍 때문에 혼란이 오는 것 같습니다..!
그리고 return 값이 필요하지 않다면 forEach가 조금 더 의도에 맞을 것 같습니당

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. 매개변수명을 Object라고 한 이유는 일반 배열이 아닌 객체배열이라서 저렇게 썼던 것이었습니다. (그냥 저의 인식일 뿐이었습니다.)
    object와 array를 섞어서 사용하니 혼란이 야기될 수 있는 것일까요??? 가르침을 주시면 감사하겠습니다 ㅎ

  2. map과 forEach 조금 더 공부해서 적절한 적용을 해볼 수 있도록 하겠습니다. 알려주셔서 감사합니다!!!


startCarRacing(carNamesObject, tryNumber) {
let racingResult = carNamesObject;
for (let i = 0; i < tryNumber; i++) {
racingResult = racingResult.map((object) => {
if (this.getRandomNumber() > 4) object.forward += 1;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

자동차는 랜덤 값이 4이상일 경우 전진한다.

4도 포함하도록 수정해야할 것 같습니다 :)

return object;
});
this.printGameProgress(racingResult);
}
return racingResult;
}

printWinner(carRacingResult) {
const maxForwardNumber = Math.max(
...carRacingResult.map((object) => object.forward)
);
Comment on lines +93 to +95
Copy link

@xxziiko xxziiko Nov 25, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

스프레드 연산자를 사용할 때는 ...변수명 이런식으로 하는게 조금 더 가독성에 좋다고 생각되는데, 이부분에 대해서는 어떻게 생각하시는지 궁금해요!
해당 함수가 정확히 어떤 요소를 return 하는지 네이밍함으로서 배열의 요소가 더 명확해 질 수 있을거라고 생각합니다!

const forwardSteps = carRacingResult.map((car) => car.forward)
const maxForwardNumber = Math.max(...forwardSteps);

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

너무 좋은 코드인데요?! 저는 제 머릿속으로 생각해내지 못한거라서요~ 배우고 가겠습니다

const winnerArray = carRacingResult
.filter((object) => object.forward === maxForwardNumber)
.map((object) => object.name);
const winner = winnerArray.join(", ");
return MissionUtils.Console.print(`최종우승자 : ${winner}`);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

출력만 하는 거니 return을 하지 않아도 될거 같아요!

}
}

export default RacingController;
5 changes: 5 additions & 0 deletions src/utils/makeArrayFromString.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const makeArrayFromString = (stringValue) => {
return stringValue.split(',');
}

export default makeArrayFromString;
8 changes: 8 additions & 0 deletions src/utils/makeObjectFromArray.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const makeObjectFromArray = (array) => {
const objectedValue = array.map((array) => {
return {name : array, forward : 0};
})
return objectedValue;
}

export default makeObjectFromArray;
11 changes: 11 additions & 0 deletions src/validation/functions/validateEmpty.js

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

functions내의 파일들의 함수들을 하나의 파일에서 관리해도 좋을 거 같아요. 공통적으로 사용되는 validation을 한파일에서 관리하면 더 편할 거 같아요!

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저도 같은 생각입니다!

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

맞습니다 ㅠ 여기서 시간이 오래걸렸었고, 비효율적이네요~
validation 만드는 방법을 바꾸는 중입니다!

Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import ERROR_MESSAGES from "../../constants/errorMessages.js";

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

우테코에서 airbnb Javascript 컨벤션을 따르라고 권장을 하였는데, airbnb 컨벤션에서는 쌍따옴표를 권장하지 않더라고요!
single quotes로 작성하면 좋을 것 같습니다~!
참고로 prettier에 설정하면 자동으로 변환해주어서 편하게 저는 이용하고 있어요~!

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

prettier 수정 당장 해보겠습니다.


const validateEmpty = (value) => {
if (value == "") {
throw new Error(ERROR_MESSAGES.VALIDATE_EMPTY);
}

return true;
};

export default validateEmpty;
16 changes: 16 additions & 0 deletions src/validation/functions/validateFiveLength.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import ERROR_MESSAGES from "../../constants/errorMessages.js";
import makeArrayFromString from "../../utils/makeArrayFromString.js";

const validateFiveLength = (value) => {
const carNamesArray = makeArrayFromString(value);
carNamesArray.forEach((carName) => {
if (carName.length > 5) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저도 자꾸 놓치는 부분인데, 5가 매직넘버가 될 수 있으니 상수처리해주면 좋을 것 같아요~
예를 들어 MIN_CARNAME_LENGTH와 같이 하면 어떨까요 ~?

throw new Error(ERROR_MESSAGES.VALIDATE_FIVE_LENGTH);
}
});

return true;
};

export default validateFiveLength;

11 changes: 11 additions & 0 deletions src/validation/functions/validateLimitNumber.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import ERROR_MESSAGES from "../../constants/errorMessages.js";

const validateLimitNumber = (value) => {
const numberValue = Number(value);
if(numberValue > 20)
throw new Error(ERROR_MESSAGES.VALIDATE_LIMIT_NUMBER);

Comment on lines +5 to +7

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오호 제한을 20자 이하로 한 이유가 따로 있을까요 ?? 👀

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

과도한 시도횟수도 validation 하자는 생각이었습니다.

return true;
}

export default validateLimitNumber;
12 changes: 12 additions & 0 deletions src/validation/functions/validateRegEx.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import ERROR_MESSAGES from "../../constants/errorMessages.js";

const validateRegEx = (value, regExPattern) => {
const validInclusion = regExPattern.test(value);

if (!validInclusion) {
throw new Error(ERROR_MESSAGES.VALIDATE_NOT_CORRECT_REGEX);
}
return true;
};

export default validateRegEx;
13 changes: 13 additions & 0 deletions src/validation/validateCarNames.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import validateEmpty from "./functions/validateEmpty.js";
import validateFiveLength from "./functions/validateFiveLength.js";
import validateRegEx from "./functions/validateRegEx.js";

const validateCarNames = (validateTarget) => {
validateEmpty(validateTarget);
const regExPattern = /^(\w+)(,\w+)*$/;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

정규식을 굉장히 잘사용하시는군요,,,!!
제가 개인적으로 정규식을 어려워해서 덕분에 좋은 패턴 알아갑니다!

validateRegEx(validateTarget, regExPattern);
validateFiveLength(validateTarget);
return true;
}

export default validateCarNames;
13 changes: 13 additions & 0 deletions src/validation/validateTryNumber.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import validateEmpty from "./functions/validateEmpty.js";
import validateLimitNumber from "./functions/validateLimitNumber.js";
import validateRegEx from "./functions/validateRegEx.js";

const validateTryNumber = (validationTarget) => {
validateEmpty(validationTarget);
const regExPattern = /^\d{1,2}$/;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

자리수 제한을 정규식으로도 할 수 있네요! 배워갑니다👍

validateRegEx(validationTarget, regExPattern);
validateLimitNumber(validationTarget);
return true;
};

export default validateTryNumber;