summaryrefslogtreecommitdiff
path: root/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java
blob: 0251de3417a7d834f136d5dc18196601cc17455f (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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
package bjc.utils.funcdata;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;

import bjc.utils.data.IHolder;
import bjc.utils.data.IPair;
import bjc.utils.data.Identity;
import bjc.utils.data.Pair;

/**
 * A wrapper over another list that provides eager functional operations
 * over it. 
 *
 * Differs from a stream in every way except for the fact that
 * they both provide functional operations.
 * 
 * @author ben
 *
 * @param <E>
 *            The type in this list
 */
public class FunctionalList<E> implements Cloneable, IList<E> {
	/*
	 * The list used as a backing store
	 */
	private List<E> wrapped;

	/**
	 * Create a new empty functional list.
	 */
	public FunctionalList() {
		wrapped = new ArrayList<>();
	}

	/**
	 * Create a new functional list containing the specified items.
	 * 
	 * Takes O(n) time, where n is the number of items specified
	 * 
	 * @param items
	 *            The items to put into this functional list.
	 */
	@SafeVarargs
	public FunctionalList(E... items) {
		wrapped = new ArrayList<>(items.length);

		for (E item : items) {
			wrapped.add(item);
		}
	}

	/**
	 * Create a new functional list with the specified size.
	 * 
	 * @param size
	 *            The size of the backing list .
	 */
	private FunctionalList(int size) {
		wrapped = new ArrayList<>(size);
	}

	/**
	 * Create a new functional list as a wrapper of a existing list.
	 * 
	 * Takes O(1) time, since it doesn't copy the list.
	 * 
	 * @param backing
	 *            The list to use as a backing list.
	 */
	public FunctionalList(List<E> backing) {
		if (backing == null) {
			throw new NullPointerException(
					"Backing list must be non-null");
		}

		wrapped = backing;
	}

	@Override
	public boolean add(E item) {
		return wrapped.add(item);
	}

	@Override
	public boolean allMatch(Predicate<E> predicate) {
		if (predicate == null) {
			throw new NullPointerException("Predicate must be non-null");
		}

		for (E item : wrapped) {
			if (!predicate.test(item)) {
				// We've found a non-matching item
				return false;
			}
		}

		// All of the items matched
		return true;
	}

	@Override
	public boolean anyMatch(Predicate<E> predicate) {
		if (predicate == null) {
			throw new NullPointerException("Predicate must be not null");
		}

		for (E item : wrapped) {
			if (predicate.test(item)) {
				// We've found a matching item
				return true;
			}
		}

		// We didn't find a matching item
		return false;
	}

	/**
	 * Clone this list into a new one, and clone the backing list as well
	 * 
	 * Takes O(n) time, where n is the number of elements in the list
	 * 
	 * @return A list
	 */
	@Override
	public IList<E> clone() {
		IList<E> cloned = new FunctionalList<>();

		for (E element : wrapped) {
			cloned.add(element);
		}

		return cloned;
	}

	@Override
	public <T, F> IList<F> combineWith(IList<T> rightList,
			BiFunction<E, T, F> itemCombiner) {
		if (rightList == null) {
			throw new NullPointerException( "Target combine list must not be null");
		} else if (itemCombiner == null) {
			throw new NullPointerException("Combiner must not be null");
		}

		IList<F> returned = new FunctionalList<>();

		// Get the iterator for the other list
		Iterator<T> rightIterator = rightList.toIterable().iterator();

		for (Iterator<E> leftIterator = wrapped.iterator();
				leftIterator.hasNext() && rightIterator.hasNext();) {
			// Add the transformed items to the result list
			E leftVal = leftIterator.next();
			T rightVal = rightIterator.next();

			returned.add(itemCombiner.apply(leftVal, rightVal));
		}

		return returned;
	}

	@Override
	public boolean contains(E item) {
		// Check if any items in the list match the provided item
		return this.anyMatch(item::equals);
	}

	@Override
	public E first() {
		if (wrapped.size() < 1) {
			throw new NoSuchElementException("Attempted to get first element of empty list");
		}

		return wrapped.get(0);
	}

	@Override
	public <T> IList<T> flatMap(Function<E, IList<T>> expander) {
		if (expander == null) {
			throw new NullPointerException("Expander must not be null");
		}

		IList<T> returned = new FunctionalList<>(this.wrapped.size());

		forEach(element -> {
			IList<T> expandedElement = expander.apply(element);

			if (expandedElement == null) {
				throw new NullPointerException("Expander returned null list");
			}

			// Add each element to the returned list
			expandedElement.forEach(returned::add);
		});

		return returned;
	}

	public void forEach(Consumer<E> action) {
		if (action == null) {
			throw new NullPointerException("Action is null");
		}

		wrapped.forEach(action);
	}

	@Override
	public void forEachIndexed(BiConsumer<Integer, E> indexedAction) {
		if (indexedAction == null) {
			throw new NullPointerException("Action must not be null");
		}

		// This is held b/c ref'd variables must be final/effectively final
		IHolder<Integer> currentIndex = new Identity<>(0);

		wrapped.forEach((element) -> {
			// Call the action with the index and the value
			indexedAction.accept(currentIndex.unwrap(index -> index), element);

			// Increment the value
			currentIndex.transform((index) -> index + 1);
		});
	}

	@Override
	public E getByIndex(int index) {
		return wrapped.get(index);
	}

	/**
	 * Get the internal backing list.
	 * 
	 * @return The backing list this list is based off of.
	 */
	public List<E> getInternal() {
		return wrapped;
	}

	@Override
	public IList<E> getMatching(Predicate<E> predicate) {
		if (predicate == null) {
			throw new NullPointerException("Predicate must not be null");
		}

		IList<E> returned = new FunctionalList<>();

		wrapped.forEach((element) -> {
			if (predicate.test(element)) {
				// The item matches, so add it to the returned list
				returned.add(element);
			}
		});

		return returned;
	}

	@Override
	public int getSize() {
		return wrapped.size();
	}

	@Override
	public boolean isEmpty() {
		return wrapped.isEmpty();
	}

	/*
	 * Check if a partition has room for another item
	 */
	private Boolean isPartitionFull(int numberPerPartition,
			IHolder<IList<E>> currentPartition) {
		return currentPartition.unwrap((partition) -> partition.getSize() >= numberPerPartition);
	}

	@Override
	public <T> IList<T> map(Function<E, T> elementTransformer) {
		if (elementTransformer == null) {
			throw new NullPointerException("Transformer must be not null");
		}

		IList<T> returned = new FunctionalList<>(this.wrapped.size());

		forEach(element -> {
			// Add the transformed item to the result
			returned.add(elementTransformer.apply(element));
		});

		return returned;
	}

	@Override
	public <T> IList<IPair<E, T>> pairWith(IList<T> rightList) {
		return combineWith(rightList, Pair<E, T>::new);
	}

	@Override
	public IList<IList<E>> partition(int numberPerPartition) {
		if (numberPerPartition < 1
				|| numberPerPartition > wrapped.size()) {
			throw new IllegalArgumentException("" + numberPerPartition
					+ " is an invalid partition size. Must be between 1 and "
					+ wrapped.size());
		}

		IList<IList<E>> returned = new FunctionalList<>();

		// The current partition being filled
		IHolder<IList<E>> currentPartition = new Identity<>(
				new FunctionalList<>());

		this.forEach((element) -> {
			if (isPartitionFull(numberPerPartition, currentPartition)) {
				// Add the partition to the list
				returned.add(currentPartition.unwrap((partition) -> partition));

				// Start a new partition
				currentPartition.transform((partition) -> new FunctionalList<>());
			} else {
				// Add the element to the current partition
				currentPartition.unwrap((partition) -> partition.add(element));
			}
		});

		return returned;
	}

	@Override
	public void prepend(E item) {
		wrapped.add(0, item);
	}

	@Override
	public E randItem(Function<Integer, Integer> rnd) {
		if (rnd == null) {
			throw new NullPointerException("Random source must not be null");
		}

		int randomIndex = rnd.apply(wrapped.size());

		return wrapped.get(randomIndex);
	}

	@Override
	public <T, F> F reduceAux(T initialValue,
			BiFunction<E, T, T> stateAccumulator,
			Function<T, F> resultTransformer) {
		if (stateAccumulator == null) {
			throw new NullPointerException("Accumulator must not be null");
		} else if (resultTransformer == null) {
			throw new NullPointerException("Transformer must not be null");
		}

		// The current collapsed list
		IHolder<T> currentState = new Identity<>(initialValue);

		wrapped.forEach(element -> {
			// Accumulate a new value into the state
			currentState.transform((state) -> stateAccumulator.apply(element, state));
		});

		// Convert the state to its final value
		return currentState.unwrap(resultTransformer);
	}

	@Override
	public boolean removeIf(Predicate<E> removePredicate) {
		if (removePredicate == null) {
			throw new NullPointerException("Predicate must be non-null");
		}

		return wrapped.removeIf(removePredicate);
	}

	@Override
	public void removeMatching(E desiredElement) {
		removeIf((element) -> element.equals(desiredElement));
	}

	@Override
	public void reverse() {
		Collections.reverse(wrapped);
	}

	@Override
	public E search(E searchKey, Comparator<E> comparator) {
		// Search our internal list
		int foundIndex = Collections.binarySearch(wrapped, searchKey,
				comparator);

		if (foundIndex >= 0) {
			// We found a matching element
			return wrapped.get(foundIndex);
		}

		// We didn't find an element
		return null;
	}

	@Override
	public void sort(Comparator<E> comparator) {
		// sb.deleteCharAt(sb.length() - 2);
		Collections.sort(wrapped, comparator);
	}

	@Override
	public IList<E> tail() {
		return new FunctionalList<>(wrapped.subList(1, getSize()));
	}

	@Override
	public E[] toArray(E[] arrType) {
		return wrapped.toArray(arrType);
	}

	@Override
	public Iterable<E> toIterable() {
		return wrapped;
	}

	@Override
	public String toString() {
		int lSize = getSize();

		if(lSize == 0) return "()";

		StringBuilder sb = new StringBuilder("(");
		Iterator<E> itr = toIterable().iterator();
		E itm = itr.next();
		int i = 0;

		if(lSize == 1) {
			return "(" + itm + ")";
		}

		for(E item : toIterable()) {
			sb.append(item.toString());

			if(i < lSize-1) {
				sb.append(", ");
			}

			i += 1;
		}

		sb.append(")");
		return sb.toString();
	}
}