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

[문자열 덧셈 계산기] 이나영 미션 제출합니다. #572

Open
wants to merge 36 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
6f0da34
docs: README 문구 추가
Bewheneverwhatiwant Oct 17, 2024
f2f9c42
docs: REACME 내용 보완 - branch 전략 추가
Bewheneverwhatiwant Oct 17, 2024
d2b9264
docs: README 브랜치 전략 수정
Bewheneverwhatiwant Oct 18, 2024
fe7259c
feat: 빈 문자열 입력 시 0 반환 기능 추가
Bewheneverwhatiwant Oct 20, 2024
249df5a
docs: README 내용 추가 - 이슈 자동닫힘->수동닫음으로 전략 변경
Bewheneverwhatiwant Oct 20, 2024
316cc8f
feat: 쉼표구분자 문자열 입력 시 연산 기능 추가
Bewheneverwhatiwant Oct 20, 2024
e1020e0
docs: README 일부 내용 삭제
Bewheneverwhatiwant Oct 20, 2024
7dabd65
docs: README 개행 수정
Bewheneverwhatiwant Oct 20, 2024
7abe52f
feat: 쉼표 또는 콜론 구분자의 문자열 입력 시 연산 기능 추가
Bewheneverwhatiwant Oct 20, 2024
4ed98a0
feat: 커스텀 구분자 지원 기능 추가
Bewheneverwhatiwant Oct 20, 2024
f526e61
feat: 음수, 숫자가 아닌 값, 잘못된입력 처리 기능 추가
Bewheneverwhatiwant Oct 20, 2024
c2100f7
docs: README에 사용자 입력 겨우의 수 내용 추가
Bewheneverwhatiwant Oct 20, 2024
a36fc48
docs: README 개행 분리
Bewheneverwhatiwant Oct 20, 2024
614215e
refactor: run() 내부 try catch로 수정, 컨벤션에 따른 수정
Bewheneverwhatiwant Oct 20, 2024
08968bb
feat: 커스텀 구분자와 기본 구분자를 혼용해도 연산 가능하도록 기능 추가
Bewheneverwhatiwant Oct 20, 2024
3b9b3f9
docs: README 기능 및 사용자 경우의 수 추가
Bewheneverwhatiwant Oct 20, 2024
a87d260
chore(ApplicationTest): 테스트케이스(쉼표 구분자)추가
Bewheneverwhatiwant Oct 20, 2024
8068e41
chore(ApplicationTest): 테스트케이스(zhffhs rnqnswk) 추가
Bewheneverwhatiwant Oct 20, 2024
ca88274
chore(ApplicationTest): 테스트케이스(콜론 구분자) 추가
Bewheneverwhatiwant Oct 20, 2024
41788bd
Merge branch 'bewheneverwhatiwant' of https://github.com/Bewheneverwh…
Bewheneverwhatiwant Oct 20, 2024
bc4ca74
chore(ApplicationTest): 테스트케이스(커스텀 구분자만 입력하는 경우) 추가
Bewheneverwhatiwant Oct 20, 2024
865940c
chore(ApplicationTest): 테스트케이스(커스텀 구분자가 /,\,\n인 경우) 추가
Bewheneverwhatiwant Oct 20, 2024
1560c40
style: AirBnB 가이드에 맞춰 큰따옴표를 작은따옴표로 변경
Bewheneverwhatiwant Oct 20, 2024
62aec6b
style(App): AirBnB 가이드에 맞춰 큰따옴표를 작은따옴표로 변경
Bewheneverwhatiwant Oct 20, 2024
ed58de9
Merge branch 'bewheneverwhatiwant' of https://github.com/Bewheneverwh…
Bewheneverwhatiwant Oct 20, 2024
ebb788a
refactor(App): 3개의 함수들을 별도 파일로 분리
Bewheneverwhatiwant Oct 20, 2024
acf275e
refactor(all): 파일 구조를 폴더로 정리
Bewheneverwhatiwant Oct 20, 2024
6975470
refactor(add): 2개 함수를 별도 파일로 분리
Bewheneverwhatiwant Oct 20, 2024
5578dc8
docs(README): 프로그램 흐름을 정리한 내용 추가
Bewheneverwhatiwant Oct 20, 2024
a32249e
docs(README): 오타 및 개행 수정
Bewheneverwhatiwant Oct 20, 2024
fc27c21
docs(README): 디렉토리 구조 설명 추가
Bewheneverwhatiwant Oct 20, 2024
7127a59
docs(README): 개행 수정
Bewheneverwhatiwant Oct 20, 2024
8db452d
docs(README): 기능들의 상위 기능 정의
Bewheneverwhatiwant Oct 20, 2024
540ce83
docs(README): 개행 수정
Bewheneverwhatiwant Oct 20, 2024
593ae60
docs(README): 개행 수정
Bewheneverwhatiwant Oct 20, 2024
a651bc2
refactor(all): eslint.config.js 파일에 따른 eslint적용
Bewheneverwhatiwant Oct 21, 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
58 changes: 7 additions & 51 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,63 +1,19 @@
import { getInput } from './getInput.js';
import { add } from './add.js';
import { printResult } from './printResult.js';
import { Console } from '@woowacourse/mission-utils';

class App {
async run() {

Choose a reason for hiding this comment

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

저는 try-catch로 에러 핸들링하는 것을 생각 못했는데 보고 배워갑니다 ㅎㅎ

Choose a reason for hiding this comment

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

제가 매 코드마다 try-catch를 재탕(?)하는 버릇이 있어서...ㅎㅎ 이 구조가 가장 보기좋다는 인식이 있어서 바로 적용할 수 있었어요 !! 칭찬해주셔서 너무 감사드립니다 🍀

Choose a reason for hiding this comment

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

jaeyoung-kwon님 혹시 woowa 저장소 풀리퀘 주소 남겨주시면 제가 거기서 코드리뷰 해드릴 수 있을 것 같아요 !! 이 답글 보신다면 PR 번호나 주소 남겨주시면 맞리뷰 해드리구 싶습니다 😄

try {
const input = await this.getInput();
const result = this.add(input);
this.printResult(result);
const input = await getInput();
const result = add(input);
printResult(result);
} catch (error) {
Console.print(`${error.message}`);
throw error; // 예외를 다시 던져서 테스트에서 잡히도록 처리
throw error; // 예외를 다시 던져서 테스트에서 잡히도록 처리
}

Choose a reason for hiding this comment

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

간결한 run 함수 너무 깔끔하네요!
저는 어차피 에러를 처리하지 못하고 throw 하므로 try, catch는 굳이 사용하지 않아도 된다고 생각했어요
에러 객체를 throw 하기때문에 에러 메시지도 콘솔에 출력하지 않아도 될 것 같아요

Choose a reason for hiding this comment

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

아...! 제가 생각치 못했던 부분이네요 ! 깔끔함과 익숙함에 취해서 '이유'를 생각하지 않은 코딩이었던 것 같아요 ㅠㅠ 2주차 미션에서는 더 고민해서 App.js 구조를 작성해보겠습니다 !!

}

async getInput() {
const input = await Console.readLineAsync('덧셈할 문자열을 입력해 주세요.\n');
return input;
}

add(input) {
if (input === "") {
return 0;
}

let delimiter = /[,|:]/; // 기본 구분자 설정

if (input.startsWith("//")) {
const parts = input.split("\\n");

// 커스텀 구분자만 입력하거나 숫자 미입력의 경우 대응
if (parts.length < 2 || parts[1].trim() === "") {
throw new Error('[ERROR] 잘못된 입력 형식입니다.');
}

// 커스텀 구분자가 /, \, \n인 경우 구분자로 설정되도록 대응
// 사용자가 커스텀 구분자와 기본 구분자를 혼용해도 연산이 이뤄지도록 수정
const customDelimiter = parts[0].slice(2).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
delimiter = RegExp(`[${customDelimiter},:]`);
input = parts[1];
}

const numbers = input
.split(delimiter)
.filter(num => num !== "") // 구분자가 중복되어도 연산되도록 필터링
.map(num => {
const parsedNum = Number(num);
if (isNaN(parsedNum)) {
throw new Error('[ERROR] 숫자가 아닌 값이 포함되었습니다.');
} else if (parsedNum < 0) {
throw new Error('[ERROR] 양수로만 이루어져야 합니다.');
}
return parsedNum;
});

return numbers.reduce((sum, num) => sum + num, 0);
}

printResult(result) {
Console.print(`결과 : ${result}`);
}
}

export default App;
34 changes: 34 additions & 0 deletions src/add.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
export function add(input) {
if (input === "") {
return 0;
}

let delimiter = /[,|:]/; // 기본 구분자 설정

if (input.startsWith("//")) {
const parts = input.split("\\n");

if (parts.length < 2 || parts[1].trim() === "") {
throw new Error('[ERROR] 잘못된 입력 형식입니다.');
}

const customDelimiter = parts[0].slice(2).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
delimiter = RegExp(`[${customDelimiter},:]`);
input = parts[1];
}

const numbers = input
.split(delimiter)
.filter(num => num !== "") // 구분자가 중복되어도 연산되도록 필터링
.map(num => {
const parsedNum = Number(num);
if (isNaN(parsedNum)) {
throw new Error('[ERROR] 숫자가 아닌 값이 포함되었습니다.');
} else if (parsedNum < 0) {
throw new Error('[ERROR] 양수로만 이루어져야 합니다.');
}
return parsedNum;
});

return numbers.reduce((sum, num) => sum + num, 0);
}

Choose a reason for hiding this comment

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

마지막에 로직을 분리하는 커밋을 보면서 디렉토리 구조에 신경쓰는 것 같다는 생각이 들었어요.
App.js에서 run 메서드에 연산 관련 로직이 순서대로 들어가있는 것처럼 보입니다
별도의 객체를 생성해서 객체의 기능을 따로 묶어두는건 어떨까요?
물론 이번 과제에서는 계산기에서 단순히 덧셈 기능만 있기 때문에 꼭 필요하다고는 생각하지 않습니다.
하지만, 객체로 분리해서 기능들을 관리하는 방식이 유지보수나 확장성 측면에서 더 유용할 것이라는 생각이 들어요

물론 저도 객체의 기능을 어디까지 결정해야할지는 아직 고민이 많지만 제가 가지고 있는 생각을 말씀드려봤습니다. 이 내용이 하나의 아이디어가 되었으면 좋겠어요!

Choose a reason for hiding this comment

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

정말 좋은 지적이세요 !! 다른 분들의 코드를 봐도, 저처럼 하신 분들도 계시지만 객체지향적으로 코드를 작성하신 불들이 많으시더라고요. 파일을 둘러봐도, OOP 스럽게 쓰신 코드는 읽기 편하고 다른 케이스를 적용하기도 좋아보였어요. 다음 미션에서는 더 OOP 스러운 코드 작성을 시도하겠습니다 !!

6 changes: 6 additions & 0 deletions src/getInput.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { Console } from '@woowacourse/mission-utils';

export async function getInput() {
const input = await Console.readLineAsync('덧셈할 문자열을 입력해 주세요.\n');
return input;
}
5 changes: 5 additions & 0 deletions src/printResult.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Console } from '@woowacourse/mission-utils';

export function printResult(result) {
Console.print(`결과 : ${result}`);
}