Skip to content

Commit

Permalink
Comparable Versjon (#396)
Browse files Browse the repository at this point in the history
  • Loading branch information
oyvemb authored Nov 21, 2023
1 parent e13b21b commit 383caf8
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
25 changes: 24 additions & 1 deletion soknad/src/main/java/no/nav/k9/søknad/felles/Versjon.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package no.nav.k9.søknad.felles;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import jakarta.validation.constraints.Pattern;
Expand All @@ -9,7 +11,7 @@
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonValue;

public class Versjon {
public class Versjon implements Comparable<Versjon> {

@JsonIgnore
private static final String SEMVER_REGEX = "(\\d+)\\.(\\d+)\\.(\\d+)";
Expand Down Expand Up @@ -44,6 +46,27 @@ public boolean erGyldig() {
return verdi.matches(SEMVER_REGEX);
}

@Override
public int compareTo(Versjon that) {
if (!this.erGyldig() || !that.erGyldig()) {
throw new IllegalArgumentException("Ugyldig format på Versjon");
}

List<Integer> thisComponents = Arrays.stream(this.verdi.split("\\."))
.map(Integer::parseInt).toList();
List<Integer> thatComponents = Arrays.stream(that.verdi.split("\\."))
.map(Integer::parseInt).toList();

for (int i=0; i<3; i++) {
Integer thisVersjonstall = thisComponents.get(i);
Integer thatVersjonstall = thatComponents.get(i);
if (!Objects.equals(thisVersjonstall, thatVersjonstall)) {
return thisVersjonstall.compareTo(thatVersjonstall);
}
}
return 0;
}

@Override
public boolean equals(Object obj) {
if (obj == this)
Expand Down
16 changes: 16 additions & 0 deletions soknad/src/test/java/no/nav/k9/søknad/felles/VersjonTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package no.nav.k9.søknad.felles;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;

class VersjonTest {

@Test
void sammenligneVersjoner() {
assertThat(Versjon.of("2.0.0")).isGreaterThan(Versjon.of("1.9.9"));
assertThat(Versjon.of("1.2.0")).isGreaterThan(Versjon.of("1.1.9"));
assertThat(Versjon.of("1.1.2")).isGreaterThan(Versjon.of("1.1.1"));
assertThat(Versjon.of("1.1.1")).isEqualTo(Versjon.of("1.1.1"));
}
}

0 comments on commit 383caf8

Please sign in to comment.