Skip to content

Commit dc0f405

Browse files
l1cachejbgi
authored andcommitted
few useful function added to Ord class as well
1 parent 7a30ac7 commit dc0f405

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

core/src/main/java/fj/Ord.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,39 @@ public final Ord<A> reverse() {
287287
return ordDef(def.dual());
288288
}
289289

290+
/**
291+
* Constructs an ord instance, which compares using self and if objects are equal compares using <code>ord</code>
292+
*
293+
* @param ord Ord for subsequent comparison
294+
* @return A new equal instance
295+
*/
296+
public final Ord<A> andThen(final Ord<A> ord) {
297+
return ordDef((a1, a2) -> {
298+
final Ordering compareResult = compare(a1, a2);
299+
if(compareResult == Ordering.EQ)
300+
return ord.compare(a1, a2);
301+
return compareResult;
302+
});
303+
}
304+
305+
/**
306+
* Constructs an ord instance, which compares using self and if objects are equal compares the mapped objects
307+
*
308+
* @param f The function to map the original object
309+
* @param ord Ord for the mapped object
310+
* @return A new equal instance
311+
*/
312+
public final <B> Ord<A> andThen(final F<A, B> f, final Ord<B> ord) {
313+
return andThen(ord.contramap(f));
314+
}
315+
316+
/**
317+
* Static version of {@link #contramap(F)}
318+
*/
319+
public static <A, B> Ord<A> contramap(final F<A, B> f, final Ord<B> ord) {
320+
return ord.contramap(f);
321+
}
322+
290323
/**
291324
* Returns an order instance that uses the given equality test and ordering function.
292325
*

core/src/test/java/fj/OrdTest.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,22 @@ public void isLessThan() {
2424
assertThat(pred.f(1L), is(false));
2525
assertThat(pred.f(2L), is(false));
2626
}
27+
28+
@Test
29+
public void contramapShouldWork() {
30+
Ord<String> lengthOrd = Ord.contramap(String::length, Ord.intOrd);
31+
32+
assertThat(lengthOrd.compare("str", "rts"), is(Ordering.EQ));
33+
assertThat(lengthOrd.compare("strlong", "str"), is(Ordering.GT));
34+
}
35+
36+
@Test
37+
public void andThenShouldWork() {
38+
Ord<String> lengthThenLastDigitOrd = Ord.contramap(String::length, Ord.intOrd)
39+
.andThen(s -> s.charAt(s.length() - 1), Ord.charOrd);
40+
41+
assertThat(lengthThenLastDigitOrd.compare("str", "dyr"), is(Ordering.EQ));
42+
assertThat(lengthThenLastDigitOrd.compare("stt", "str"), is(Ordering.GT));
43+
assertThat(lengthThenLastDigitOrd.compare("str", "strr"), is(Ordering.LT));
44+
}
2745
}

0 commit comments

Comments
 (0)