Skip to content

Commit 98123ad

Browse files
committed
Add support for result() method
1 parent f7fa08f commit 98123ad

File tree

3 files changed

+35
-1
lines changed

3 files changed

+35
-1
lines changed

src/main/java/com/github/underscore/_.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -927,6 +927,21 @@ public static String unescape(String value) {
927927
return value.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&quot;", "\"").replaceAll("&amp;", "&");
928928
}
929929

930+
public static <E> Object result(final Iterable<E> iterable, final Predicate<E> pred) {
931+
for (E element : iterable) {
932+
if (pred.apply(element)) {
933+
if (element instanceof Map.Entry) {
934+
if (((Map.Entry) element).getValue() instanceof Function) {
935+
return ((Function) ((Map.Entry) element).getValue()).apply();
936+
}
937+
return ((Map.Entry) element).getValue();
938+
}
939+
return element;
940+
}
941+
}
942+
return null;
943+
}
944+
930945
public static <E> Template<Set<E>> template(final String template) {
931946
return new Template<Set<E>>(template) {
932947
@Override

src/test/java/com/github/underscore/_Test.java

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1332,7 +1332,26 @@ public void result() throws Exception {
13321332
put("stuff", new Function<String>() { public String apply() { return "nonsense"; }});
13331333
}};
13341334

1335-
// _.result(object.entrySet(), asList("cheese"));
1335+
assertEquals("crumpets", _.result(object.entrySet(), new Predicate<Map.Entry<String, Object>>() {
1336+
public Boolean apply(Map.Entry<String, Object> item) {
1337+
return item.getKey().equals("cheese");
1338+
}
1339+
}));
1340+
assertEquals("nonsense", _.result(object.entrySet(), new Predicate<Map.Entry<String, Object>>() {
1341+
public Boolean apply(Map.Entry<String, Object> item) {
1342+
return item.getKey().equals("stuff");
1343+
}
1344+
}));
1345+
assertEquals("result1", _.result(asList("result1", "result2"), new Predicate<String>() {
1346+
public Boolean apply(String item) {
1347+
return item.equals("result1");
1348+
}
1349+
}));
1350+
assertEquals(null, _.result(asList("result1", "result2"), new Predicate<String>() {
1351+
public Boolean apply(String item) {
1352+
return item.equals("result3");
1353+
}
1354+
}));
13361355
}
13371356

13381357
/*

underscore.jar

205 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)