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