-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathApp.js
More file actions
117 lines (99 loc) · 2.99 KB
/
Copy pathApp.js
File metadata and controls
117 lines (99 loc) · 2.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import { Console } from "@woowacourse/mission-utils";
class Calculator {
constructor() {
this.basicSeparators = ",:";
this.customSeparator = null;
}
validateHeader(userInput) {
if (userInput == null || userInput === "") {
return "";
}
const headerRegex = new RegExp(/^\/\/(.)\\n/);
const header = userInput.match(headerRegex);
if (header) {
if (/[0-9]/.test(header[1])) {
throw new Error(
"잘못된 커스텀 구분자 형식입니다. - 커스텀 구분자는 숫자가 될 수 없습니다."
);
}
this.customSeparator = header[1];
const headerlessInput = userInput.substring(5);
return headerlessInput;
}
if (userInput.startsWith("//")) {
throw new Error(
"잘못된 커스텀 구분자 형식입니다. - 커스텀 구분자 입력 형식은 '//<구분자>\\n'입니다."
);
}
return userInput;
}
validateInput(input) {
if (input === "") {
return "";
}
const separator = this.customSeparator
? this.customSeparator
: this.basicSeparators;
const allowedRegex = new RegExp(`^[0-9${separator}]+$`);
if (!allowedRegex.test(input)) {
throw new Error("잘못된 입력 형식입니다. - 구분자 외 다른 문자가 존재");
}
return input;
}
splitBySeparators(input) {
if (input === "") {
return [];
}
const splitRegex = new RegExp(`[${this.basicSeparators}]`);
return this.customSeparator
? input.split(this.customSeparator)
: input.split(splitRegex);
}
validateArray(arr) {
if (arr.length === 0) {
return;
}
if (arr.some((element) => element === "")) {
throw new Error("잘못된 입력 형식입니다. - 구분자 사이에 숫자가 없음");
}
const intRegex = /^\d+$/;
for (const element of arr) {
if (!intRegex.test(element)) {
throw new Error("잘못된 입력 형식입니다. - 숫자 이외의 문자가 포함됨");
}
}
}
sum(numberArr) {
return numberArr.reduce((acc, num) => Number(acc) + Number(num), 0);
}
calculate(userInput) {
try {
const normalized = (userInput ?? "").replace(/[^\S\n]+/g, "");
const headerlessInput = this.validateHeader(normalized);
const validatedInput = this.validateInput(headerlessInput);
const splitedStrArray = this.splitBySeparators(validatedInput);
this.validateArray(splitedStrArray);
return this.sum(splitedStrArray);
} catch (err) {
throw new Error(err.message);
}
}
}
class App {
constructor() {
this.calculator = new Calculator();
}
async run() {
try {
const userInput = await Console.readLineAsync(
"덧셈할 문자열을 입력해 주세요. \n"
);
const result = this.calculator.calculate(userInput);
Console.print(`결과 : ${result}`);
} catch (err) {
const errorMessage = `[ERROR] ${err.message}`;
throw new Error(errorMessage);
}
}
}
export default App;