Skip to content

Commit 9724589

Browse files
committed
feat: Metadata::mergeIfEqualElse
1 parent 0a5d88f commit 9724589

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

  • src/main/java/org/variantsync/diffdetective/metadata

src/main/java/org/variantsync/diffdetective/metadata/Metadata.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import java.nio.file.Path;
1111
import java.util.LinkedHashMap;
1212
import java.util.Map;
13+
import java.util.function.BiFunction;
1314

1415
/**
1516
* Generic interface to model composable and printable metadata.
@@ -67,6 +68,37 @@ static <T> T mergeEqual(T a, T b) {
6768
return b;
6869
}
6970

71+
/**
72+
* Same as {@link #mergeEqual(Object, Object)} but does not crash when the two values are unequal.
73+
* Instead, both values are merged using the supplied function.
74+
* The supplied function is called only if the two given values are unequal (according to {@link Object::equals}).
75+
*
76+
* <p>The value {@code null} is treated as the neutral element in the sense that no exception is
77+
* thrown if an element is {@code null}. In this case return value is defined by {@code
78+
* mergeIfEqualElse(a, null, f) == a} and {@code mergeIfEqualElse(b, null, f) == b}.
79+
*
80+
* @param a the first element to merge
81+
* @param b the second element to merge
82+
* @param ifUnequal merge operator called when the two values are unequal
83+
* @param <T> the type of the objects to be merged
84+
* @return {@code a} if both given values are equal, otherwise the result of {@code ifUnequal.apply(a, b)}
85+
*/
86+
static <T> T mergeIfEqualElse(T a, T b, BiFunction<T, T, T> ifUnequal) {
87+
if (b == null) {
88+
return a;
89+
}
90+
91+
if (a == null) {
92+
return b;
93+
}
94+
95+
if (a.equals(b)) {
96+
return a;
97+
} else {
98+
return ifUnequal.apply(a, b);
99+
}
100+
}
101+
70102
/**
71103
* Prints all key-value pairs to a single string.
72104
* Falls back to {@link #show(String, Object)} on each entry.

0 commit comments

Comments
 (0)