All Downloads are FREE. Search and download functionalities are using the official Maven repository.

generator.server.javatool.memoizers.main.Memoizers.mustache Maven / Gradle / Ivy

There is a newer version: 1.22.0
Show newest version
package {{packageName}}.shared.memoizer.domain;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Supplier;
import {{packageName}}.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) {}
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy