-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathArithmeticNode.java
119 lines (89 loc) · 2.5 KB
/
ArithmeticNode.java
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
118
119
package org.codefx.demo.junit5.dynamic;
import java.util.List;
import java.util.function.Supplier;
import java.util.function.ToLongFunction;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import static java.util.Objects.requireNonNull;
/**
* A simplified version of a node in a tree that adds and multiplies longs.
*/
interface ArithmeticNode {
long evaluate();
List<ArithmeticNode> operands();
static ArithmeticNode operationFor(ArithmeticOperator operator, ArithmeticNode... operands) {
return new OperationNode(operator, operands);
}
static ArithmeticNode valueOf(long value) {
return new ValueNode(value);
}
class OperationNode implements ArithmeticNode {
private final ArithmeticOperator operator;
private final ArithmeticNode[] operands;
private OperationNode(ArithmeticOperator operator, ArithmeticNode[] operands) {
this.operator = requireNonNull(operator);
this.operands = requireNonNull(operands);
}
@Override
public long evaluate() {
long[] operandValues = Stream.of(operands)
.mapToLong(ArithmeticNode::evaluate)
.toArray();
return operator.evaluate(operandValues);
}
@Override
public List<ArithmeticNode> operands() {
return List.of(operands);
}
@Override
public String toString() {
return operator.toString();
}
}
class ValueNode implements ArithmeticNode {
private final long value;
private ValueNode(long value) {
this.value = value;
}
@Override
public long evaluate() {
return value;
}
@Override
public List<ArithmeticNode> operands() {
return List.of();
}
@Override
public String toString() {
return "Value " + value;
}
}
enum ArithmeticOperator {
MULTIPLY(
operands -> LongStream
.of(operands)
// implementation error to make tests interesting
.map(operand -> operand % 10 == 0 ? operand / 10 : operand)
.reduce(1, (o1, o2) -> o1 * o2),
() -> "Multiplication"),
ADD(
operands -> LongStream
.of(operands)
// implementation error to make tests interesting
.map(operand -> operand == 4 ? 3 : operand)
.sum(),
() -> "Addition");
private final ToLongFunction<long[]> compute;
private final Supplier<String> toString;
ArithmeticOperator(ToLongFunction<long[]> compute, Supplier<String> toString) {
this.compute = compute;
this.toString = toString;
}
public long evaluate(long... operands) {
return compute.applyAsLong(operands);
}
public String toString() {
return toString.get();
}
}
}