summaryrefslogtreecommitdiff
path: root/BJC-Utils2/src/main/java/bjc/utils/funcutils/GroupPartIteration.java
blob: 229d2716c1637e83ca5c152b569f397c47705142 (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
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.IList;

/**
 * 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 IList<IList<E>>			returnedList;

	private IHolder<IList<E>>		currentPartition;
	private IList<E>				rejectedItems;

	private IHolder<Integer>		numberInCurrentPartition;
	private int						numberPerPartition;

	private Function<E, Integer>	elementCounter;

	public GroupPartIteration(IList<IList<E>> returned,
			IHolder<IList<E>> currPart, IList<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);

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