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

com.github.dakusui.printables.PrintableFunctionals Maven / Gradle / Ivy

The newest version!
package com.github.dakusui.printables;

import com.github.dakusui.actionunit.utils.InternalUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;

import static com.github.dakusui.actionunit.utils.InternalUtils.summary;
import static com.github.dakusui.actionunit.utils.InternalUtils.toStringIfOverriddenOrNoname;

public enum PrintableFunctionals {
  ;

  public static  PrintablePredicate.Builder printablePredicate(Predicate predicate) {
    return new PrintablePredicate.Builder<>(predicate);
  }

  public static  PrintableConsumer.Builder printableConsumer(Consumer consumer) {
    return new PrintableConsumer.Builder<>(consumer);
  }

  public static  PrintableFunction.Builder printableFunction(Function function) {
    return new PrintableFunction.Builder<>(function);
  }

  public static  Predicate isKeyOf(Map values) {
    return printablePredicate((Predicate) values::containsKey)
        .describe(() -> String.format("isKeyOf[%s]", summary(values.toString())));
  }

  public static  Function memoize(Function function) {
    return printableFunction(new Function() {
      final Map cache = new ConcurrentHashMap<>();

      @Override
      public O apply(I i) {
        return cache.computeIfAbsent(i, function);
      }
    }).describe(InternalUtils.toStringIfOverriddenOrNoname(function));
  }

  public static  Consumer functionToConsumer(Function function) {
    return printableConsumer(function::apply)
        .describe(toStringIfOverriddenOrNoname(function));
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy