Skip to content

Commit

Permalink
refactor(iter): when if
Browse files Browse the repository at this point in the history
  • Loading branch information
jesperolsson-se committed May 3, 2024
1 parent 17ab5d6 commit c583cf6
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/main/java/org/schemaspy/util/WhenIf.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package org.schemaspy.util;

import java.util.function.Consumer;
import java.util.function.Predicate;

public class WhenIf<T> implements Predicate<T> {

private final Predicate<T> origin;
private final Consumer<T> onTrue;
private final Consumer<T> onFalse;

public WhenIf(
final Predicate<T> origin,
final Consumer<T> onTrue,
final Consumer<T> onFalse
) {
this.origin = origin;
this.onTrue = onTrue;
this.onFalse = onFalse;
}

@Override
public boolean test(final T t) {
if (this.origin.test(t)) {
this.onTrue.accept(t);
return true;
} else {
this.onFalse.accept(t);
return false;
}
}
}
37 changes: 37 additions & 0 deletions src/test/java/org/schemaspy/util/WhenIfTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package org.schemaspy.util;

import java.util.concurrent.atomic.AtomicBoolean;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;

/**
* Tests for {@link WhenIf}.
*/
class WhenIfTest {

@Test
void actOnFalse() {
AtomicBoolean onTrue = new AtomicBoolean(false);
AtomicBoolean onFalse = new AtomicBoolean(false);
new WhenIf<>(
a -> false,
b -> onTrue.set(true),
c -> onFalse.set(true)
).test(new Object());
assertThat(onTrue).isFalse();
assertThat(onFalse).isTrue();
}

@Test
void actOnTrue() {
AtomicBoolean onTrue = new AtomicBoolean(false);
AtomicBoolean onFalse = new AtomicBoolean(false);
new WhenIf<>(
a -> true,
b -> onTrue.set(true),
c -> onFalse.set(true)
).test(new Object());
assertThat(onTrue).isTrue();
assertThat(onFalse).isFalse();
}
}

0 comments on commit c583cf6

Please sign in to comment.