Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[자동차 경주] 박건홍 미션 제출합니다. #737

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
15 changes: 15 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
1. 자동차의 이름을 입력받는 기능
1-1. 자동차의 이름은 ","로 구분되어야 한다.
1-2. 자동차의 이름에 공백이 들어가서는 안 된다.
1-3. 자동차가 최소 2개 이상일 때(자동차의 이름이 두 개 이상일 때) 경주가 시작된다.
1-4. 자동차의 이름은 최대 5자이다.
1-5. 자동차의 이름은 중복될 수 없다.

2. 이동 횟수를 입력받는 기능
2-1. 이동 횟수는 0보다 커야한다.
2-2. 이동 횟수 입력값에 공백이 있어서는 안 된다.
2-3. 이동 횟수 입력값에 숫자가 아닌 문자가 들어가선 안 된다.

3. 각 이동 회차마다 자동차를 이동하고 상태를 출력하는 기능
4. 회차가 마무리되고 우승자를 판별하는 기능
5. 우승자를 출력하는 기능
84 changes: 83 additions & 1 deletion src/App.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,87 @@
import { MissionUtils } from "@woowacourse/mission-utils";

class App {
async play() {}

nameValidation(input) {

Choose a reason for hiding this comment

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

Suggested change
nameValidation(input) {
validateCarNames(input) {

일부 케이스를 제외하고는 보통 메소드나 함수명은 동사형으로 짓는 것 같은데, 동사형 이름은 어떠신가요?

let names = new Map();
const inputArray = input.split(",");
if (input.includes(' ')) throw new Error("[ERROR] 공백을 제외하고 입력해주세요.");
if (input.includes(',,')) throw new Error("[ERROR] 쉼표가 연달아 입력되었습니다.");
if (inputArray.length <= 1) throw new Error("[ERROR] 2개 이상의 자동차가 있어야 시작할 수 있습니다.");
inputArray.forEach((item) => {
if (item.length > 5) throw new Error("[ERROR] 5자 이하로 입력해주세요.");
if (names.has(item)) throw new Error("[ERROR] 중복된 이름이 있습니다.");
Comment on lines +8 to +13

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.

잘게 나누면 로직이 일정 구간 별로 묶이면서 읽는 입장에서 이해하기가 수월하더라구요

names.set(item, "");
});
return names;
}

roundValidation(input) {
let rounds = 0;
if (input === "") throw new Error("[ERROR] 입력값이 없습니다.");
if (input.includes(' ')) throw new Error("[ERROR] 공백을 제외하고 입력해주세요.");
if (isNaN(input)) throw new Error("[ERROR] 숫자만 입력해주세요.");
const stringArray = Array.from(input);
stringArray.forEach((elements) => {
rounds = (rounds * 10) + parseInt(elements);
});
return rounds;
}

async playerInput() {
try{
const nameinput = await MissionUtils.Console.readLineAsync('경주할 자동차 이름을 입력하세요.(이름은 쉼표(,) 기준으로 구분)\n');
const names = this.nameValidation(nameinput);
const numberinput = await MissionUtils.Console.readLineAsync('시도할 횟수는 몇 회인가요?');
const rounds = this.roundValidation(numberinput);
return [names, rounds];
} catch(error){
MissionUtils.Console.print(error.message);
throw new Error();
}
}

diceLogic(names, rounds) {
let i = rounds;

Choose a reason for hiding this comment

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

round 수와 같은 정보는 App 클래스의 프로퍼티로 다루는 것도 괜찮을 것 같다는 생각이 들었습니다!

while(i != 0) {
names.forEach((value, key, map) => {
const num = MissionUtils.Random.pickNumberInRange(0, 9);

Choose a reason for hiding this comment

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

이 랜덤 수를 뽑는 로직을 별도의 함수로 분리하면 어떨까요?

if (num >= 4) map.set(key, value+"-");
MissionUtils.Console.print(`${key} : ${map.get(key)}`);

Choose a reason for hiding this comment

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

결과를 출력하는 이 부분도 분리해볼 수 있을 것 같아요!

});
i -= 1;
}
const winners = this.whoWin(names);
return winners;
}

whoWin (names){
const winners = [];
const ranking = Array.from(names);
ranking.sort((a, b) => b[1].length - a[1].length);
ranking.forEach((value, index, array) => {
if (index === 0) winners.push(value[0]);
if (index > 0 && array[0][1] === value[1]) winners.push(value[0]);
}
);
return winners;
}

announceWinner (winners){
const announce = winners.join(', ');
MissionUtils.Console.print(`최종 우승자 : ${announce}`);
}

async play() {
try {
const stuffs = await this.playerInput();

Choose a reason for hiding this comment

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

혹시 stuffs라는 변수명을 지으신 이유가 있으신가요~? 변수명은 최대한 명확한 게 좋다고 들어서 stuffs와 같이 불분명한 이름 대신 확실하게 의미가 드러나는 단어로 지어보시면 가독성에 도움이 될 것 같습니다!

또, 자바스크립트에서 배열로부터 값을 꺼내는 아래와 같은 문법도 있으니 참고해보시면 좋을 것 같아요!

Suggested change
const stuffs = await this.playerInput();
const [names, rounds] = await this.playerInput();

const winners = await this.diceLogic(stuffs[0], stuffs[1]);
this.announceWinner(winners);
} catch (error){}
}
}

const app = new App();
app.play();

export default App;