diff --git a/src/main/java/ic/doc/IntOperator.java b/src/main/java/ic/doc/IntOperator.java new file mode 100644 index 0000000..df24beb --- /dev/null +++ b/src/main/java/ic/doc/IntOperator.java @@ -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, Integer> operator; + + IntOperator(int operands, Function, Integer> operator) { + this.operands = operands; + this.operator = operator; + } + + public int evaluate(List arguments) { + if (arguments.size() != operands) { + throw new IllegalArgumentException( + String.format("Expected %d arguments, got %d", operands, arguments.size()) + ); + } + return operator.apply(arguments); + } +} diff --git a/src/test/java/ic/doc/IntOperatorTest.java b/src/test/java/ic/doc/IntOperatorTest.java new file mode 100644 index 0000000..796aa8c --- /dev/null +++ b/src/test/java/ic/doc/IntOperatorTest.java @@ -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 + } + } +}