forked from erdos/stencil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBasicFunctions.java
87 lines (77 loc) · 2.66 KB
/
BasicFunctions.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
79
80
81
82
83
84
85
86
87
package io.github.erdos.stencil.functions;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* Common general purpose functions.
*/
@SuppressWarnings("unused")
public enum BasicFunctions implements Function {
/**
* Selects value based on first argument.
* Usage: switch(expression, case-1, value-1, case-2, value-2, ..., optional-default-value)
*/
SWITCH {
@Override
public Object call(Object... arguments) {
if (arguments.length < 3) {
throw new IllegalArgumentException("switch() function expects at least 3 args!");
}
final Object expr = arguments[0];
for (int i = 1; i < arguments.length; i += 2) {
final Object value = arguments[i];
final Object result = arguments[i + 1];
if (expr == null && value == null)
return result;
else if (expr != null && expr.equals(value))
return result;
}
if (arguments.length % 2 == 0) {
return arguments[arguments.length - 1];
} else {
return null;
}
}
},
/**
* Returns the first non-null a non-empty value.
* <p>
* Accepts any arguments. Skips null values, empty strings and empty collections.
*/
COALESCE {
@Override
public Object call(Object... arguments) {
for (Object arg : arguments)
if (arg != null && !"".equals(arg) && (!(arg instanceof Collection) || !((Collection) arg).isEmpty()))
return arg;
return null;
}
},
/**
* Returns true iff input is null, empty string or empty collection.
* <p>
* Expects exactly 1 argument.
*/
EMPTY {
@Override
public Object call(Object... arguments) {
if (arguments.length != 1)
throw new IllegalArgumentException("empty() function expects exactly 1 argument, " + arguments.length + " given.");
Object x = arguments[0];
return (x == null || "".equals(x))
|| ((x instanceof Collection) && ((Collection) x).isEmpty())
|| ((x instanceof Iterable) && !((Iterable) x).iterator().hasNext());
}
};
@Override
public String getName() {
return name().toLowerCase();
}
public static class Provider implements FunctionProvider {
private static final List<Function> FUNCTIONS = Arrays.asList(values());
@Override
public Collection<Function> functions() {
return FUNCTIONS;
}
}
}