summaryrefslogtreecommitdiff
path: root/src/main/java/bjc/everge/ReplSet.java
blob: a477456b715fddb2de2560a15e31ae5b52e4862f (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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package bjc.everge;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * A set of ReplPairs, kept together for easy use
 *
 * @author Ben Culkin
 */
public class ReplSet {
	// The list of pairs
	private List<ReplPair> parList;

	/**
	 * Create a new blank set of pairs.
	 */
	public ReplSet() {
		parList = new ArrayList<>();
	}

	/**
	 * Create a new set of pairs using an existing list of pairs.
	 *
	 * Changes to the list of pairs will carry across to the ReplSet, so be careful about that.
	 *
	 * @param lst
	 * 		The list of pairs to use.
	 */
	public ReplSet(List<ReplPair> lst) {
		parList = lst;
	}

	public static ReplSet fromFile(String fName) throws IOException {
		ReplSet rs = new ReplSet();

		try (FileInputStream fis = new FileInputStream(fName); Scanner scn = new Scanner(fis)) {
			rs.parList = ReplPair.readList(scn);
		}

		return rs;
	}

	/**
	 * Adds more pairs to the ReplSet.
	 *
	 * @param pars
	 * 	The pairs to add to the ReplSet.
	 */
	public void addPairs(List<ReplPair> pars) {
		for (ReplPair par : pars) {
			parList.add(par);
		}

		// Resort the pairs into priority order
		parList.sort(null);
	}

	/**
	 * Adds more pairs to the ReplSet.
	 *
	 * @param pars
	 * 	The pairs to add to the ReplSet.
	 */
	public void addPairs(ReplPair... pars) {
		for (ReplPair par : pars) {
			parList.add(par);
		}

		// Resort the pairs into priority order
		parList.sort(null);
	}

	/**
	 * Apply the ReplSet to a string.
	 *
	 * @param val
	 * 		The string to apply the ReplSet to.
	 *
	 * @return The result of applying the ReplSet.
	 */
	public String apply(String val) {
		String ret = val;

		for (ReplPair par : parList) {
			ret = par.apply(ret);
		}

		return ret;
	}
}