|
| 1 | +package domain; |
| 2 | + |
| 3 | +import java.security.InvalidParameterException; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.function.BiFunction; |
| 6 | + |
| 7 | +public enum Operator { |
| 8 | + PLUS("+", (left, right) -> left + right), |
| 9 | + SUBTRACT("-", (left, right) -> left - right), |
| 10 | + MULTIPLY("*", (left, right) -> left * right), |
| 11 | + DIVIDE("/", (left, right) -> left / right); |
| 12 | + |
| 13 | + private String symbol; |
| 14 | + private BiFunction<Integer, Integer, Integer> biFunction; |
| 15 | + |
| 16 | + Operator(String symbol, BiFunction<Integer, Integer, Integer> biFunction) { |
| 17 | + this.symbol = symbol; |
| 18 | + this.biFunction = biFunction; |
| 19 | + } |
| 20 | + |
| 21 | + public Integer calculate(int left, int right) { |
| 22 | + if (this == DIVIDE && right == 0) { |
| 23 | + throw new InvalidParameterException("0으로 나눌 수 없습니다."); |
| 24 | + } |
| 25 | + return biFunction.apply(left, right); |
| 26 | + } |
| 27 | + |
| 28 | + public static Operator toOperation(String symbol) { |
| 29 | + return Arrays.stream(values()) |
| 30 | + .filter(operator -> operator.symbol.equals(symbol)) |
| 31 | + .findAny() |
| 32 | + .orElseThrow(() -> new InvalidParameterException("유효한 연산자가 아닙니다.")); |
| 33 | + } |
| 34 | +} |
0 commit comments