IntOperator implementation with evaluation and argument count checking.
Co-Authored-By: td1223
This commit is contained in:
parent
84f1c2bb86
commit
9f5a89a63f
|
@ -0,0 +1,23 @@
|
||||||
|
package ic.doc;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.function.Function;
|
||||||
|
|
||||||
|
public class IntOperator {
|
||||||
|
private final int operands;
|
||||||
|
private final Function<List<Integer>, Integer> operator;
|
||||||
|
|
||||||
|
IntOperator(int operands, Function<List<Integer>, Integer> operator) {
|
||||||
|
this.operands = operands;
|
||||||
|
this.operator = operator;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int evaluate(List<Integer> arguments) {
|
||||||
|
if (arguments.size() != operands) {
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
String.format("Expected %d arguments, got %d", operands, arguments.size())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return operator.apply(arguments);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,28 @@
|
||||||
|
package ic.doc;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
|
import static org.hamcrest.Matchers.is;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
|
public class IntOperatorTest {
|
||||||
|
@Test
|
||||||
|
public void intOperatorCanEvaluate() {
|
||||||
|
IntOperator intOperator = new IntOperator(2, arguments -> arguments.get(0) + arguments.get(1));
|
||||||
|
assertThat(intOperator.evaluate(List.of(1, 2)), is(3));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void intOperatorThrowsOnInvalidArguments() {
|
||||||
|
IntOperator intOperator = new IntOperator(2, arguments -> arguments.get(0) + arguments.get(1));
|
||||||
|
try {
|
||||||
|
intOperator.evaluate(List.of(1));
|
||||||
|
fail("Expected IllegalArgumentException to be thrown on invalid number of arguments");
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
// good
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue