summaryrefslogtreecommitdiff
path: root/BJC-Utils2/src/main/java/bjc/utils/funcutils/TokenSplitter.java
blob: 41760882c4ef84f2ab3c9c078210c631382ad89b (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
package bjc.utils.funcutils;

import java.util.Iterator;
import java.util.function.BiFunction;

import bjc.utils.funcdata.FunctionalList;
import bjc.utils.funcdata.IList;

final class TokenSplitter implements BiFunction<String, String, IList<String>> {
	private String tokenToSplit;

	public TokenSplitter(String tok) {
		this.tokenToSplit = tok;
	}

	@Override
	public IList<String> apply(String operatorName, String operatorRegex) {
		if (operatorName == null) {
			throw new NullPointerException("Operator name must not be null");
		} else if (operatorRegex == null) {
			throw new NullPointerException("Operator regex must not be null");
		}

		if (tokenToSplit.contains(operatorName)) {
			if (StringUtils.containsOnly(tokenToSplit, operatorRegex)) {
				return new FunctionalList<>(tokenToSplit);
			}

			IList<String> splitTokens = new FunctionalList<>(tokenToSplit.split(operatorRegex));
			IList<String> result = new FunctionalList<>();

			Iterator<String> itr = splitTokens.toIterable().iterator();
			int tokenExpansionSize = splitTokens.getSize();

			String elm = itr.next();

			for (int i = 0; itr.hasNext(); elm = itr.next()) {
				result.add(elm);

				if (i != tokenExpansionSize) {
					result.add(operatorName);
				}
			}

			return result;
		}

		return new FunctionalList<>(tokenToSplit);
	}
}