Skip to content
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
13 changes: 12 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,12 @@
# javascript-calculator-precourse
# javascript-calculator-precourse

## 기능 목록

1. 사용자의 입력을 받아 문자열을 처리한다
2. 기본 구분자(쉼표 `,` 또는 콜론 `:`)를 기준으로 숫자를 추출한다.
3. 추출한 숫자들의 합을 계산하여 반환한다.
4. 커스텀 구분자 기능을 지원한다.
- 문자열 앞부분에 `//구분자\n` 형식이 포함된 경우 해당 구분자를 사용하여 숫자를 분리한다.
5. 입력값이 비어있을 경우 `0`을 반환한다.
6. 입력값이 숫자가 아닌 경우 예외(`IllegalArgumentException`)를 발생시킨다.
7. `@woowacourse/mission-utils`의 `Console.readLineAsync`를 사용하여 입력을 받고, `Console.print`를 사용하여 결과를 출력한다.
47 changes: 46 additions & 1 deletion src/App.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,50 @@
import { Console } from "@woowacourse/mission-utils";

class App {
async run() {}

escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
async play() {

try {
const input = await Console.readLineAsync("덧셈할 문자열을 입력해 주세요.\n");
// 사용자가 입력한 "\n"을 실제 개행 문자로 치환
const replacedInput = input.replace(/\\n/g, "\n");
const trimmedInput = replacedInput.trim();
const result = this.calculate(trimmedInput);
Console.print(`결과 : ${result}`);
} catch (error) {
Console.print(error.message);
}

}

calculate(input) {
if (!input) return 0;

let delimiter = /[,:]/;
const customDelimeterMatch = input.match(/^\/\/(.)\n(.*)/);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

26행에서 (/^//(.)\n(.*)/)이 무슨 뜻인지 알 수 있을까요?
코드를 직접 돌려봤는데 실행이 잘 안 되는 거 같아서
이 부분이 무슨 뜻인지 알고 싶네요!


if (customDelimeterMatch) {
const escapedDelimiter = this.escapeRegExp(customDelimeterMatch[1])
delimiter = new RegExp(escapedDelimiter);
input = customDelimeterMatch[2];
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

이 부분 잘 이해가 안 가서 혹시 설명해주실 수 있으신가요?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

match()는 자바스크립트에서 문자열(String) 객체에 내장된 메서드로 문자열 안에서 찾고자 하는 패턴을 정규 표현식을 이용해 검색하는 함수입니다. /^//(.)\n(.*)/ 의 정규 표현식에 매칭되도록 배열을 반환합니다. 위 코드에서 customDelimeterMatch[1] 은 Delimeter(예를 들면 ;)이 대입이 되어 있고 customDelimeterMatch[2]에는 사용자가 입력한 덧셈 식이 대입되어 있습니다.(예를 들면 1;2;3) match함수에 대해서는 스터디 정리글에서 자세히 다뤄보도록 하겠습니다!

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

아앗 그리고 저 부분 오타입니닷,,,,RergExp가 아니라 RegExp에요 급해서 디버깅 안하고 내버려서^.^;;;; 사실 틀린 코드여서 안돌아갑니닷....

const numbers = input.split(delimiter).map(num => {
const parsed = Number(num);
if (isNaN(parsed) || parsed < 0 ) {
throw new Error("IllegalArgumentException: 잘못된 입력값입니다.");
}
return parsed;
});

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

map을 사용해서 배열을 순회하여 Number를 적용하셨네요
저는 reduce과정에서 Number를 적용하여 배열 순회를 덜하도록 코드를 작성했어요
const sum = inputArr.reduce((acc, cur) => {
const num = Number(cur);
(...)
}, 0);

이렇게 하면 시간복잡도 측면에서 조금 더 효율적이라고 하더라구요
근데 물론 큰 차이는 없는거 같긴 해요..ㅎㅎ

}

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

export default App;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

index없이 하나의 파일로 합치셨네요!
코드길이가 길지 않아서 이런 구조도 괜찮은 거 같습니다