From 9f5a89a63f274464d0abfe88d5c77d97716bb9f9 Mon Sep 17 00:00:00 2001 From: Gleb Koval Date: Tue, 5 Nov 2024 16:43:58 +0000 Subject: [PATCH] IntOperator implementation with evaluation and argument count checking. Co-Authored-By: td1223 --- src/main/java/ic/doc/IntOperator.java | 23 +++++++++++++++++++ src/test/java/ic/doc/IntOperatorTest.java | 28 +++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 src/main/java/ic/doc/IntOperator.java create mode 100644 src/test/java/ic/doc/IntOperatorTest.java 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 + } + } +}