tech.jhipster.lite.shared.memoizer.domain.Memoizers Maven / Gradle / Ivy
package tech.jhipster.lite.shared.memoizer.domain;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Supplier;
import tech.jhipster.lite.shared.error.domain.Assert;
public final class Memoizers {
private Memoizers() {}
public static Supplier of(Supplier supplier) {
Assert.notNull("supplier", supplier);
return () -> of(__ -> supplier.get()).apply(null);
}
public static Function of(Function function) {
Assert.notNull("function", function);
return new MemoizedFunction<>(function);
}
private static class MemoizedFunction implements Function {
private final Function function;
private final Map, MemoizedResult> results = new ConcurrentHashMap<>();
public MemoizedFunction(Function function) {
this.function = function;
}
@Override
public Result apply(Input input) {
return results.computeIfAbsent(new MemoizedInput<>(input), this::toMemoizedResult).result();
}
private MemoizedResult toMemoizedResult(MemoizedInput input) {
return new MemoizedResult<>(function.apply(input.input()));
}
private record MemoizedInput(Input input) {}
private record MemoizedResult(Result result) {}
}
}