summaryrefslogtreecommitdiff
path: root/BJC-Utils2/src/main/java/bjc/utils/funcutils/GroupPartIteration.java
blob: 383785863983830426835db35640291557e0cd5a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package bjc.utils.funcutils;

import java.util.function.Consumer;
import java.util.function.Function;

import bjc.utils.data.IHolder;
import bjc.utils.funcdata.FunctionalList;
import bjc.utils.funcdata.IFunctionalList;

/**
 * Implements a single group partitioning pass on a list
 * 
 * @author ben
 *
 * @param <E>
 *            The type of element in the list being partitioned
 */
final class GroupPartIteration<E>
		implements Consumer<E> {
	private IFunctionalList<IFunctionalList<E>>	returnedList;
	private IHolder<IFunctionalList<E>>			currentPartition;
	private IFunctionalList<E>					rejectedItems;
	private IHolder<Integer>					numberInCurrentPartition;
	private int									numberPerPartition;
	private Function<E, Integer>				elementCounter;

	public GroupPartIteration(
			IFunctionalList<IFunctionalList<E>> returned,
			IHolder<IFunctionalList<E>> currPart,
			IFunctionalList<E> rejects, IHolder<Integer> numInCurrPart,
			int nPerPart, Function<E, Integer> eleCount) {
		this.returnedList = returned;
		this.currentPartition = currPart;
		this.rejectedItems = rejects;
		this.numberInCurrentPartition = numInCurrPart;
		this.numberPerPartition = nPerPart;
		this.elementCounter = eleCount;
	}

	@Override
	public void accept(E value) {
		if (numberInCurrentPartition
				.unwrap((number) -> number >= numberPerPartition)) {
			returnedList.add(
					currentPartition.unwrap((partition) -> partition));

			currentPartition
					.transform((partition) -> new FunctionalList<>());
			numberInCurrentPartition.transform((number) -> 0);
		} else {
			int currentElementCount = elementCounter.apply(value);

			if (numberInCurrentPartition.unwrap((number) -> (number
					+ currentElementCount) >= numberPerPartition)) {
				rejectedItems.add(value);
			} else {
				currentPartition
						.unwrap((partition) -> partition.add(value));
				numberInCurrentPartition.transform(
						(number) -> number + currentElementCount);
			}
		}
	}
}