Skip to content

Commit 383caf8

Browse files
authored
Comparable Versjon (#396)
1 parent e13b21b commit 383caf8

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

soknad/src/main/java/no/nav/k9/søknad/felles/Versjon.java

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package no.nav.k9.søknad.felles;
22

3+
import java.util.Arrays;
4+
import java.util.List;
35
import java.util.Objects;
46

57
import jakarta.validation.constraints.Pattern;
@@ -9,7 +11,7 @@
911
import com.fasterxml.jackson.annotation.JsonIgnore;
1012
import com.fasterxml.jackson.annotation.JsonValue;
1113

12-
public class Versjon {
14+
public class Versjon implements Comparable<Versjon> {
1315

1416
@JsonIgnore
1517
private static final String SEMVER_REGEX = "(\\d+)\\.(\\d+)\\.(\\d+)";
@@ -44,6 +46,27 @@ public boolean erGyldig() {
4446
return verdi.matches(SEMVER_REGEX);
4547
}
4648

49+
@Override
50+
public int compareTo(Versjon that) {
51+
if (!this.erGyldig() || !that.erGyldig()) {
52+
throw new IllegalArgumentException("Ugyldig format på Versjon");
53+
}
54+
55+
List<Integer> thisComponents = Arrays.stream(this.verdi.split("\\."))
56+
.map(Integer::parseInt).toList();
57+
List<Integer> thatComponents = Arrays.stream(that.verdi.split("\\."))
58+
.map(Integer::parseInt).toList();
59+
60+
for (int i=0; i<3; i++) {
61+
Integer thisVersjonstall = thisComponents.get(i);
62+
Integer thatVersjonstall = thatComponents.get(i);
63+
if (!Objects.equals(thisVersjonstall, thatVersjonstall)) {
64+
return thisVersjonstall.compareTo(thatVersjonstall);
65+
}
66+
}
67+
return 0;
68+
}
69+
4770
@Override
4871
public boolean equals(Object obj) {
4972
if (obj == this)
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package no.nav.k9.søknad.felles;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
class VersjonTest {
8+
9+
@Test
10+
void sammenligneVersjoner() {
11+
assertThat(Versjon.of("2.0.0")).isGreaterThan(Versjon.of("1.9.9"));
12+
assertThat(Versjon.of("1.2.0")).isGreaterThan(Versjon.of("1.1.9"));
13+
assertThat(Versjon.of("1.1.2")).isGreaterThan(Versjon.of("1.1.1"));
14+
assertThat(Versjon.of("1.1.1")).isEqualTo(Versjon.of("1.1.1"));
15+
}
16+
}

0 commit comments

Comments
 (0)