package org.zwobble.mammoth.internal.results; import org.zwobble.mammoth.Result; import org.zwobble.mammoth.internal.documents.Style; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.function.BiFunction; import java.util.function.Function; import static org.zwobble.mammoth.internal.util.Iterables.lazyConcat; import static org.zwobble.mammoth.internal.util.Iterables.lazyFlatMap; import static org.zwobble.mammoth.internal.util.Lists.eagerMap; import static org.zwobble.mammoth.internal.util.Lists.list; import static org.zwobble.mammoth.internal.util.Sets.toSet; public class InternalResult { public static InternalResult> flatMap(Iterable iterable, Function> function) { List> results = eagerMap(iterable, function); return new InternalResult<>( eagerMap(results, result -> result.value), lazyFlatMap(results, result -> result.warnings)); } public static InternalResult map( InternalResult first, InternalResult second, BiFunction function) { return new InternalResult<>( function.apply(first.value, second.value), lazyConcat(first.warnings, second.warnings)); } public static InternalResult> empty() { return new InternalResult<>(Optional.empty(), list()); } public static InternalResult success(T value) { return new InternalResult<>(value, list()); } private final T value; private final Iterable warnings; public InternalResult(T value, Iterable warnings) { this.value = value; this.warnings = warnings; } public T getValue() { return value; } public Iterable getWarnings() { return warnings; } public InternalResult map(Function function) { return new InternalResult<>(function.apply(value), warnings); } public InternalResult flatMap(Function> function) { InternalResult intermediateResult = function.apply(value); return new InternalResult<>( intermediateResult.value, lazyConcat(warnings, intermediateResult.warnings)); } public Result toResult() { Set warnings = toSet(this.warnings); return new Result() { @Override public T getValue() { return value; } @Override public Set getWarnings() { return warnings; } }; } }