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

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

There is a newer version: 6.0.1
Show newest version
package com.github.dakusui.printables;

import java.util.function.Predicate;
import java.util.function.Supplier;

import static java.lang.String.format;
import static java.util.Objects.requireNonNull;

public class PrintablePredicate implements Predicate {
  private final Predicate predicate;
  private final Supplier     formatter;

  public PrintablePredicate(Supplier formatter, Predicate predicate) {
    this.predicate = requireNonNull(predicate);
    this.formatter = requireNonNull(formatter);
  }

  @Override
  public boolean test(T t) {
    return predicate.test(t);
  }

  @Override
  public Predicate and(Predicate other) {
    requireNonNull(other);
    return createPredicate(() -> format("(%s&&%s)", formatter.get(), other), t -> predicate.test(t) && other.test(t));
  }

  @Override
  public Predicate negate() {
    return createPredicate(() -> format("!%s", formatter.get()), predicate.negate());
  }

  @Override
  public Predicate or(Predicate other) {
    requireNonNull(other);
    return createPredicate(() -> format("(%s||%s)", formatter.get(), other), t -> predicate.test(t) || other.test(t));
  }

  @Override
  public String toString() {
    return formatter.get();
  }

  protected PrintablePredicate createPredicate(Supplier formatter, Predicate predicate) {
    return new PrintablePredicate<>(formatter, predicate);
  }

  public static class Builder {

    private final Predicate predicate;

    public Builder(Predicate predicate) {
      this.predicate = requireNonNull(predicate);
    }

    public Predicate describe(Supplier formatter) {
      return new PrintablePredicate<>(requireNonNull(formatter), predicate);
    }

    public Predicate describe(String description) {
      return describe(() -> description);
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy