Clamp Function in Java (#14650)
* Clamp Function in Java * Clamp Function in Java * Clamp Function in Java * Clamp Function in Java
This commit is contained in:
parent
395857901d
commit
036409850b
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.clampfunction;
|
||||||
|
|
||||||
|
public class Clamp {
|
||||||
|
|
||||||
|
public int clamp(int value, int min, int max) {
|
||||||
|
return Math.max(min, Math.min(max, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
public double clamp(double value, double min, double max) {
|
||||||
|
return Math.max(min, Math.min(max, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T extends Comparable<T>> T clamp(T value, T min, T max) {
|
||||||
|
if (value.compareTo(min) < 0) {
|
||||||
|
return min;
|
||||||
|
} else if (value.compareTo(max) > 0) {
|
||||||
|
return max;
|
||||||
|
} else {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,40 @@
|
|||||||
|
package com.baeldung.clampfunction;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class ClampFunctionUnitTest {
|
||||||
|
|
||||||
|
Clamp clampValue = new Clamp();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValueOutsideRange_whenClamp_thenReturnLowerValue() {
|
||||||
|
assertEquals(15, clampValue.clamp(10, 15, 35));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValueWithinRange_whenClamp_thenReturnValue() {
|
||||||
|
assertEquals(20, clampValue.clamp(20, 15, 35));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenValueOutsideRange_whenClamp_thenReturnMaximumValue() {
|
||||||
|
assertEquals(35, clampValue.clamp(50, 15, 35));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDoubleValueOutsideRange_whenClamp_thenReturnMaximumValue() {
|
||||||
|
assertEquals(60.5, clampValue.clamp(75.6, 25.5, 60.5));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* This method uses the clamp() method introduced in Java 21
|
||||||
|
@Test
|
||||||
|
public void givenValueWithinRange_whenClamp_thenReturnValue() {
|
||||||
|
assertEquals(20, Math.clamp(20, 67,98));
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user