-
Notifications
You must be signed in to change notification settings - Fork 2
/
Util.java
78 lines (69 loc) · 2.43 KB
/
Util.java
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
// Copyright © 2013 Solita Oy <www.solita.fi>
// This software is released under the MIT License.
// The license text is at http://opensource.org/licenses/MIT
package fi.solita.datatree;
import java.util.*;
class Util {
public static Object[] flatten(Object[] xs) {
List<Object> results = new ArrayList<>();
flatten(results, xs);
return results.toArray(new Object[results.size()]);
}
private static void flatten(List<Object> results, Object item) {
if (item == null) {
// ignore; we consider null to be equivalent to an empty list, the same way as Clojure's nil
} else if (item.getClass().isArray()) {
Object[] xs = (Object[]) item;
flatten(results, Arrays.asList(xs));
} else if (item instanceof Iterable) {
Iterable<?> xs = (Iterable<?>) item;
for (Object x : xs) {
flatten(results, x);
}
} else {
results.add(toAllowedType(item));
}
}
private static Object toAllowedType(Object item) {
Class<?> c = item.getClass();
if (c == String.class || c == Tree.class || c == Meta.class) {
return item;
}
return item.toString();
}
public static String filterOneString(Object[] xs) {
String result = null;
for (Object x : xs) {
if (x instanceof String) {
if (result == null) {
result = (String) x;
} else {
throw new IllegalArgumentException("Cannot have more than one text string; " +
"tried to add \"" + x + "\" when already had \"" + result + "\"");
}
}
}
if (result == null) {
result = "";
}
return result;
}
public static List<Meta> filterMeta(Object[] xs) {
List<Meta> result = new ArrayList<>(xs.length);
for (Object x : xs) {
if (x instanceof Meta) {
result.add((Meta) x);
}
}
return Arrays.asList(result.toArray(new Meta[result.size()]));
}
public static List<Tree> filterTree(Object[] xs) {
List<Tree> result = new ArrayList<>(xs.length);
for (Object x : xs) {
if (x instanceof Tree) {
result.add((Tree) x);
}
}
return Arrays.asList(result.toArray(new Tree[result.size()]));
}
}