Skip to content

Commit

Permalink
Merge pull request square#113 from square/loganj/pop_pop
Browse files Browse the repository at this point in the history
Give History.Builder some more useful pop ops
  • Loading branch information
loganj committed Sep 15, 2015
2 parents 8e85fb7 + 7e1abf1 commit f79f87b
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
23 changes: 23 additions & 0 deletions flow/src/main/java/flow/History.java
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,29 @@ public Object pop() {
return entry.state;
}

/**
* Pops the history until the given state is at the top.
*
* @throws IllegalArgumentException if the given state isn't in the history.
* */
public Builder popTo(Object state) {
while (!isEmpty() && !peek().equals(state)) {
pop();
}
checkArgument(!isEmpty(), String.format("%s not found in history", state));
return this;
}

public Builder pop(int count) {
final int size = history.size();
checkArgument(count <= size,
String.format("Cannot pop %d elements, history only has %d", count, size));
while (count-- > 0) {
pop();
}
return this;
}

public History build() {
return new History(history);
}
Expand Down
47 changes: 47 additions & 0 deletions flow/src/test/java/flow/FlowTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,53 @@ class FlowDispatcher implements Flow.Dispatcher {
}
}

@Test public void builderCanPopTo() {
History.Builder builder = History.emptyBuilder();
builder.push(able);
builder.push(baker);
builder.push(charlie);
builder.popTo(able);
assertThat(builder.peek()).isSameAs(able);
}

@Test public void builderPopToExplodesOnMissingState() {
History.Builder builder = History.emptyBuilder();
builder.push(able);
builder.push(baker);
builder.push(charlie);
try {
builder.popTo(new Object());
fail("Missing state object, should have thrown");
} catch (IllegalArgumentException ignored) {
// Correct!
}
}

@Test public void builderCanPopCount() {
History.Builder builder = History.emptyBuilder();
builder.push(able);
builder.push(baker);
builder.push(charlie);
builder.pop(1);
assertThat(builder.peek()).isSameAs(baker);
builder.pop(2);
assertThat(builder.isEmpty());
}

@Test public void builderPopExplodesIfCountIsTooLarge() {
History.Builder builder = History.emptyBuilder();
builder.push(able);
builder.push(baker);
builder.push(charlie);
try {
builder.pop(4);
fail("Count is too large, should have thrown");
} catch (IllegalArgumentException ignored) {
// Success!
}

}

@Test public void historyChangesAfterListenerCall() {
final History firstHistory = History.single(new Uno());

Expand Down

0 comments on commit f79f87b

Please sign in to comment.