All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.jqwik.engine.properties.shrinking.CollectShrinkable Maven / Gradle / Ivy

There is a newer version: 1.9.1
Show newest version
package net.jqwik.engine.properties.shrinking;

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

import net.jqwik.api.*;
import net.jqwik.engine.support.*;

public class CollectShrinkable implements Shrinkable> {
	private final List> elements;
	private final Predicate> until;

	public CollectShrinkable(List> elements, Predicate> until) {
		this.elements = elements;
		this.until = until;
	}

	@Override
	public List value() {
		return createValue(elements);
	}

	private List createValue(List> elements) {
		return elements
				   .stream()
				   .map(Shrinkable::value)
				   .collect(Collectors.toList());
	}

	@Override
	public Stream>> shrink() {
		return JqwikStreamSupport.concat(
			shrinkElementsOneAfterTheOther(),
			sortElements()
		).filter(s -> until.test(s.value()));
	}

	private Stream>> shrinkElementsOneAfterTheOther() {
		List>>> shrinkPerPartStreams = new ArrayList<>();
		for (int i = 0; i < elements.size(); i++) {
			int index = i;
			Shrinkable part = elements.get(i);
			Stream>> shrinkElement = part.shrink().flatMap(shrunkElement -> {
				Optional>> shrunkCollection = collectElements(index, shrunkElement);
				return shrunkCollection
						   .map(shrunkElements -> Stream.of(createShrinkable(shrunkElements)))
						   .orElse(Stream.empty());
			});
			shrinkPerPartStreams.add(shrinkElement);
		}
		return JqwikStreamSupport.concat(shrinkPerPartStreams);
	}

	private Stream>> sortElements() {
		return ShrinkingCommons.sortElements(elements, this::createShrinkable);
	}

	private CollectShrinkable createShrinkable(List> pairSwap) {
		return new CollectShrinkable<>(pairSwap, until);
	}

	private Optional>> collectElements(int replaceIndex, Shrinkable shrunkElement) {
		List> newElements = new ArrayList<>();
		for (int i = 0; i < elements.size(); i++) {
			if (i == replaceIndex) {
				newElements.add(shrunkElement);
			} else {
				newElements.add(elements.get(i));
			}
			if (until.test(createValue(newElements))) {
				return Optional.of(newElements);
			}
		}
		return Optional.empty();
	}

	@Override
	public ShrinkingDistance distance() {
		return ShrinkingDistance.forCollection(elements);
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy