ConcurrentMapBasedIntToDoubleFunctionMemoizer extends ConcurrentMapBasedMemoizer<KEY, Double> implements IntToDoubleFunction { @Override public double applyAsDouble(final int value) { final KEY key = keyFunction.apply(value); return computeIfAbsent(key, givenKey -> Double.valueOf(function.applyAsDouble(value))) .doubleValue(); } @SuppressWarnings(CompilerWarnings.NLS)  ConcurrentMapBasedIntToDoubleFunctionMemoizer(
            final ConcurrentMap<KEY, Double> cache,
            final IntFunction<KEY> keyFunction,
            final IntToDoubleFunction function); @Override double applyAsDouble(final int value);  }
@Test public void shouldMemoizeFunction() { final ConcurrentMap<Integer, Double> cache = new ConcurrentHashMap<>(); final IntToDoubleFunction function = input -> 123; final IntFunction<Integer> keyFunction = Integer::valueOf; final ConcurrentMapBasedIntToDoubleFunctionMemoizer<Integer> memoizer = new ConcurrentMapBasedIntToDoubleFunctionMemoizer<>( cache, keyFunction, function); memoizer.applyAsDouble(123); }
@Test public void shouldUseSetCacheKeyAndValue() { final ConcurrentMap<Integer, Double> cache = new ConcurrentHashMap<>(); final IntToDoubleFunction function = input -> 123; final IntFunction<Integer> keyFunction = Integer::valueOf; final ConcurrentMapBasedIntToDoubleFunctionMemoizer<Integer> memoizer = new ConcurrentMapBasedIntToDoubleFunctionMemoizer<>( cache, keyFunction, function); memoizer.applyAsDouble(123); Assert.assertFalse("Cache is still empty after memoization", memoizer.viewCacheForTest().isEmpty()); Assert.assertEquals("Memoization key does not match expectations", 123, memoizer.viewCacheForTest().keySet().iterator().next().intValue()); Assert.assertEquals("Memoization value does not match expectations", 123D, memoizer.viewCacheForTest().values().iterator().next().doubleValue(), 0.0D); }
@Test public void shouldUseCallWrappedFunction() { final ConcurrentMap<Integer, Double> cache = new ConcurrentHashMap<>(); final IntToDoubleFunction function = Mockito.mock(IntToDoubleFunction.class); final IntFunction<Integer> keyFunction = Integer::valueOf; final ConcurrentMapBasedIntToDoubleFunctionMemoizer<Integer> memoizer = new ConcurrentMapBasedIntToDoubleFunctionMemoizer<>( cache, keyFunction, function); memoizer.applyAsDouble(123); Mockito.verify(function).applyAsDouble(123); }
@Test public void shouldUseReturnFunctionResult() { final ConcurrentMap<Integer, Double> cache = new ConcurrentHashMap<>(); final IntToDoubleFunction function = input -> 123; final IntFunction<Integer> keyFunction = Integer::valueOf; final ConcurrentMapBasedIntToDoubleFunctionMemoizer<Integer> memoizer = new ConcurrentMapBasedIntToDoubleFunctionMemoizer<>( cache, keyFunction, function); Assert.assertEquals(123D, memoizer.applyAsDouble(123), 0.0D); }