Skip to content

Commit

Permalink
Add conditional consumption methods to InputMap.
Browse files Browse the repository at this point in the history
  • Loading branch information
TomasMikula committed Aug 30, 2015
1 parent 62ccdc6 commit 42c5b63
Showing 1 changed file with 62 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.util.Arrays;
import java.util.Objects;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Stream;
Expand Down Expand Up @@ -90,6 +91,41 @@ public static <T extends Event> InputMap<T> consume(
return consume(EventPattern.eventType(eventType));
}

public static <T extends Event, U extends T> InputMap<U> consumeWhen(
EventPattern<? super T, ? extends U> eventPattern,
BooleanSupplier condition,
Consumer<? super U> action) {
return process(eventPattern, u -> {
if(condition.getAsBoolean()) {
action.accept(u);
return Result.CONSUME;
} else {
return Result.PROCEED;
}
});
}

public static <T extends Event> InputMap<T> consumeWhen(
EventType<? extends T> eventType,
BooleanSupplier condition,
Consumer<? super T> action) {
return consumeWhen(EventPattern.eventType(eventType), condition, action);
}

public static <T extends Event, U extends T> InputMap<U> consumeUnless(
EventPattern<? super T, ? extends U> eventPattern,
BooleanSupplier condition,
Consumer<? super U> action) {
return consumeWhen(eventPattern, () -> !condition.getAsBoolean(), action);
}

public static <T extends Event> InputMap<T> consumeUnless(
EventType<? extends T> eventType,
BooleanSupplier condition,
Consumer<? super T> action) {
return consumeUnless(EventPattern.eventType(eventType), condition, action);
}

public static <T extends Event, U extends T> InputMap<U> ignore(
EventPattern<? super T, ? extends U> eventPattern) {
return new PatternActionMap<>(eventPattern, PatternActionMap.CONST_IGNORE);
Expand All @@ -99,6 +135,32 @@ public static <T extends Event> InputMap<T> ignore(
EventType<? extends T> eventType) {
return ignore(EventPattern.eventType(eventType));
}

public static <T extends Event> InputMap<T> when(
BooleanSupplier condition, InputMap<T> im) {

return new InputMap<T>() {

@Override
public void forEachEventType(HandlerConsumer<? super T> f) {
HandlerConsumer<T> g = new HandlerConsumer<T>() {

@Override
public <F extends T> void accept(
EventType<? extends F> t, InputHandler<? super F> h) {
f.accept(t, evt -> condition.getAsBoolean() ? h.process(evt) : Result.PROCEED);
}

};

}
};
}

public static <T extends Event> InputMap<T> unless(
BooleanSupplier condition, InputMap<T> im) {
return when(() -> !condition.getAsBoolean(), im);
}
}

class PatternActionMap<T extends Event, U extends T> implements InputMap<U> {
Expand Down

0 comments on commit 42c5b63

Please sign in to comment.