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:
Michael Olayemi 2023-09-01 03:12:51 +00:00 committed by GitHub
parent 395857901d
commit 036409850b
2 changed files with 63 additions and 0 deletions

View File

@ -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;
}
}
}

View File

@ -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));
}
*/
}