Skip to content

Commit

Permalink
Merge pull request #361 from gdgib/G2-1507-EnumMinMax
Browse files Browse the repository at this point in the history
G2-1507 HEnum min & max methods
  • Loading branch information
gdgib authored Jan 17, 2024
2 parents 4140484 + 916b357 commit 97f5ac7
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

import com.g2forge.alexandria.java.core.marker.Helpers;
import com.g2forge.alexandria.java.function.IFunction1;
Expand Down Expand Up @@ -49,4 +50,28 @@ public static <E extends Enum<E>> Class<E> getEnumClass(E object) {
final Class<E> retVal = (Class) (((enclosing != null) && enclosing.isEnum() && enclosing.isInstance(object)) ? enclosing : klass);
return retVal;
}

@SafeVarargs
public static <E extends Enum<E>> E min(E... input) {
Objects.requireNonNull(input);
if (input.length < 1) throw new IllegalArgumentException();

E retVal = input[0];
for (int i = 1; i < input.length; i++) {
if (retVal.compareTo(input[i]) > 0) retVal = input[i];
}
return retVal;
}

@SafeVarargs
public static <E extends Enum<E>> E max(E... input) {
Objects.requireNonNull(input);
if (input.length < 1) throw new IllegalArgumentException();

E retVal = input[0];
for (int i = 1; i < input.length; i++) {
if (retVal.compareTo(input[i]) < 0) retVal = input[i];
}
return retVal;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,36 @@ public void valueOfString() {
} catch (IllegalArgumentException e) {}
Assert.assertEquals(E.C, HEnum.valueOf(E.class, Object::toString, true, IFunction1.Identity.create(), "X"));
}

@Test(expected = IllegalArgumentException.class)
public void minEmpty() {
HEnum.min();
}

@Test(expected = IllegalArgumentException.class)
public void maxEmpty() {
HEnum.max();
}

@Test
public void max1() {
Assert.assertEquals(E.A, HEnum.max(E.A));
}

@Test
public void min1() {
Assert.assertEquals(E.A, HEnum.min(E.A));
}

@Test
public void max2() {
Assert.assertEquals(E.b, HEnum.max(E.A, E.b));
Assert.assertEquals(E.C, HEnum.max(E.C, E.b));
}

@Test
public void min2() {
Assert.assertEquals(E.A, HEnum.min(E.A, E.b));
Assert.assertEquals(E.b, HEnum.min(E.C, E.b));
}
}

0 comments on commit 97f5ac7

Please sign in to comment.