View Javadoc
1   package diffblue.flipflop;
2   
3   import java.util.function.Predicate;
4   
5   import static java.util.Objects.requireNonNull;
6   
7   /**
8    * Emulates flip-flop logic similar to two-dots flip-flop in Perl or Ruby.
9    */
10  public final class FlipFlopPredicate<T> implements Predicate<T> {
11      private final Predicate<? super T> startPredicate;
12      private final Predicate<? super T> endPredicate;
13      private boolean state;
14  
15      public FlipFlopPredicate(Predicate<? super T> lhs, Predicate<? super T> rhs) {
16          this.startPredicate = requireNonNull(lhs);
17          this.endPredicate = requireNonNull(rhs);
18      }
19  
20      @Override
21      public boolean test(final T value) {
22          var result = state || startPredicate.test(value);
23          state = result && !endPredicate.test(value);
24          return result;
25      }
26  }