-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathExpression.java
More file actions
70 lines (58 loc) · 2.23 KB
/
Copy pathExpression.java
File metadata and controls
70 lines (58 loc) · 2.23 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
package calculator.model;
import calculator.utils.ExceptionConstants;
import calculator.utils.Validator;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class Expression {
private HashSet<Character> operators;
private String expression;
private static final List<Character> DEFAULT_SEPARATOR = Arrays.asList(':', ',');
private static final String OR_DELIMITER = "|";
private static final String CUSTOM_SEPARATOR_REGEX = "^//(.)\\\\n(.*)";
private static final int CUSTOM_SEPARATOR_INDEX = 1;
private static final int EXPRESSION_INDEX = 2;
public static Expression parse(String line) {
Expression expression = new Expression();
line = line.trim();
line = expression.extractOperators(line);
expression.expression = line;
return expression;
}
public HashSet<Character> getOperators() {
return operators;
}
public String getExpression() {
return expression;
}
public int calculate() {
List<String> results = Arrays.stream(expression.split(getOperatorsRegex())).toList();
results.forEach(Validator::validatePositiveInt);
try {
return results.stream()
.mapToInt(Integer::parseInt)
.reduce(0, Math::addExact);
} catch (Exception exception) {
throw new IllegalArgumentException(
ExceptionConstants.INVALID_EXPRESSION.getMessage() + expression, exception);
}
}
private String extractOperators(String line) {
this.operators = new HashSet<>();
this.operators.addAll(DEFAULT_SEPARATOR);
Matcher matcher = Pattern.compile(CUSTOM_SEPARATOR_REGEX).matcher(line);
if (matcher.find()) {
operators.add(matcher.group(CUSTOM_SEPARATOR_INDEX).charAt(0));
return matcher.group(EXPRESSION_INDEX);
}
return line;
}
private String getOperatorsRegex() {
return operators.stream()
.map((ch) -> Pattern.quote(ch.toString())) // \같은 문자 처리
.collect(Collectors.joining(OR_DELIMITER));
}
}