ConcurrentMapBasedDoubleToLongFunctionMemoizer extends ConcurrentMapBasedMemoizer<KEY, Long> implements DoubleToLongFunction { @Override public long applyAsLong(final double value) { final KEY key = keyFunction.apply(value); return computeIfAbsent(key, givenKey -> Long.valueOf(function.applyAsLong(value))) .longValue(); } @SuppressWarnings(CompilerWarnings.NLS)  ConcurrentMapBasedDoubleToLongFunctionMemoizer(
            final ConcurrentMap<KEY, Long> cache,
            final DoubleFunction<KEY> keyFunction,
            final DoubleToLongFunction function); @Override long applyAsLong(final double value);  }
@Test public void shouldMemoizeFunction() { final ConcurrentMap<Double, Long> cache = new ConcurrentHashMap<>(); final DoubleToLongFunction function = input -> 123; final DoubleFunction<Double> keyFunction = Double::valueOf; final ConcurrentMapBasedDoubleToLongFunctionMemoizer<Double> memoizer = new ConcurrentMapBasedDoubleToLongFunctionMemoizer<>( cache, keyFunction, function); memoizer.applyAsLong(123.456D); }
@Test public void shouldUseSetCacheKeyAndValue() { final ConcurrentMap<Double, Long> cache = new ConcurrentHashMap<>(); final DoubleToLongFunction function = input -> 123; final DoubleFunction<Double> keyFunction = Double::valueOf; final ConcurrentMapBasedDoubleToLongFunctionMemoizer<Double> memoizer = new ConcurrentMapBasedDoubleToLongFunctionMemoizer<>( cache, keyFunction, function); memoizer.applyAsLong(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", 123L, memoizer.viewCacheForTest().values().iterator().next().longValue()); }
@Test public void shouldUseCallWrappedFunction() { final ConcurrentMap<Double, Long> cache = new ConcurrentHashMap<>(); final DoubleToLongFunction function = Mockito.mock(DoubleToLongFunction.class); final DoubleFunction<Double> keyFunction = Double::valueOf; final ConcurrentMapBasedDoubleToLongFunctionMemoizer<Double> memoizer = new ConcurrentMapBasedDoubleToLongFunctionMemoizer<>( cache, keyFunction, function); memoizer.applyAsLong(123D); Mockito.verify(function).applyAsLong(123D); }
@Test public void shouldUseReturnFunctionResult() { final ConcurrentMap<Double, Long> cache = new ConcurrentHashMap<>(); final DoubleToLongFunction function = input -> 123; final DoubleFunction<Double> keyFunction = Double::valueOf; final ConcurrentMapBasedDoubleToLongFunctionMemoizer<Double> memoizer = new ConcurrentMapBasedDoubleToLongFunctionMemoizer<>( cache, keyFunction, function); Assert.assertEquals(123L, memoizer.applyAsLong(123D)); }