58 lines
1.6 KiB
Java
58 lines
1.6 KiB
Java
package ch.fritteli.gombaila;
|
|
|
|
import io.vavr.control.Option;
|
|
import org.jetbrains.annotations.NotNull;
|
|
|
|
import java.util.function.BiFunction;
|
|
import java.util.function.BiPredicate;
|
|
|
|
public class ElementWalker<T, E> {
|
|
@NotNull
|
|
private final T back;
|
|
@NotNull
|
|
private final BiPredicate<T, Integer> hasNextPredicate;
|
|
@NotNull
|
|
private final BiPredicate<T, Integer> hasPrevPredicate;
|
|
@NotNull
|
|
private final BiFunction<T, Integer, E> atFunction;
|
|
private int index = 0;
|
|
|
|
public ElementWalker(@NotNull final T back,
|
|
@NotNull final BiPredicate<T, Integer> hasNextPredicate,
|
|
@NotNull final BiPredicate<T, Integer> hasPrevPredicate,
|
|
@NotNull final BiFunction<T, Integer, E> atFunction) {
|
|
this.back = back;
|
|
this.hasNextPredicate = hasNextPredicate;
|
|
this.hasPrevPredicate = hasPrevPredicate;
|
|
this.atFunction = atFunction;
|
|
}
|
|
|
|
public boolean hasNext() {
|
|
return this.hasNextPredicate.test(this.back, this.index);
|
|
}
|
|
|
|
@NotNull
|
|
public E next() {
|
|
return this.atFunction.apply(this.back, this.index++);
|
|
}
|
|
|
|
@NotNull
|
|
public Option<E> peekNext() {
|
|
return Option.when(this.hasNext(), () -> this.atFunction.apply(this.back, this.index));
|
|
}
|
|
|
|
public boolean hasPrev() {
|
|
return this.hasPrevPredicate.test(this.back, this.index);
|
|
}
|
|
|
|
@NotNull
|
|
public E prev() {
|
|
return this.atFunction.apply(this.back, --this.index);
|
|
}
|
|
|
|
@NotNull
|
|
public Option<E> peekPrev() {
|
|
return Option.when(this.hasPrev(), () -> this.atFunction.apply(this.back, this.index - 1));
|
|
}
|
|
}
|