[LANG-1479] Add Range.fit(T) to fit a value into a range.

This commit is contained in:
Gary Gregory 2019-08-22 10:33:05 -04:00
parent 8a192eb6b5
commit b1d01fecee
3 changed files with 39 additions and 1 deletions

View File

@ -56,6 +56,7 @@ The <action> type attribute can be add,update,fix,remove.
<action issue="LANG-1437" type="update" dev="ggregory" due-to="Andrei Troie">Remove redundant if statements in join methods #411.</action>
<action issue="LANG-1460" type="fix" dev="kinow" due-to="Larry West">Trivial: year of release for 3.9 says 2018, should be 2019</action>
<action issue="LANG-1476" type="fix" dev="kinow" due-to="emopers">Use synchronise on a set created with Collections.synchronizedSet before iterating</action>
<action issue="LANG-1479" type="add" dev="ggregory">Add Range.fit(T) to fit a value into a range.</action>
</release>
<release version="3.9" date="2019-04-09" description="New features and bug fixes. Requires Java 8, supports Java 9, 10, 11">

View File

@ -452,6 +452,28 @@ public boolean isStartedBy(final T element) {
return comparator.compare(element, minimum) == 0;
}
/**
* <p>
* Fits the given element into this range by returning the given element or, if out of bounds, the range minimum if
* below, or the range maximum if above.
* </p>
*
* @param element the element to check for, not null
* @return the minimum, the element, or the maximum depending on the element's location relative to the range
* @since 3.10
*/
public T fit(final T element) {
// Comparable API says throw NPE on null
Validate.notNull(element, "Element is null");
if (isAfter(element)) {
return minimum;
} else if (isBefore(element)) {
return maximum;
} else {
return element;
}
}
/**
* <p>Gets the range as a {@code String}.</p>
*

View File

@ -170,6 +170,22 @@ public void testEqualsObject() {
assertNotEquals("Ni!", byteRange2);
}
@Test
public void testFit() {
assertEquals(intRange.getMinimum(), intRange.fit(Integer.MIN_VALUE));
assertEquals(intRange.getMinimum(), intRange.fit(intRange.getMinimum()));
assertEquals(intRange.getMaximum(), intRange.fit(Integer.MAX_VALUE));
assertEquals(intRange.getMaximum(), intRange.fit(intRange.getMaximum()));
assertEquals(15, intRange.fit(15));
}
@Test
public void testFitNull() {
assertThrows(NullPointerException.class, () -> {
intRange.fit(null);
});
}
@Test
public void testGetMaximum() {
assertEquals(20, (int) intRange.getMaximum());
@ -367,5 +383,4 @@ public void testToStringFormat() {
final String str = intRange.toString("From %1$s to %2$s");
assertEquals("From 10 to 20", str);
}
}