Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Comparable Versjon
Browse files Browse the repository at this point in the history
oyvemb committed Nov 21, 2023

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
1 parent 1aafc91 commit 46e19bb
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;
@@ -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+)";
@@ -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)
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 46e19bb

Please sign in to comment.