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

tech.jhipster.lite.shared.memoizer.domain.Memoizers Maven / Gradle / Ivy

There is a newer version: 1.22.0
Show newest version
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) {}
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy