Skip to content

Commit

Permalink
Merge pull request #14 from seart-group/enhancement/comparable
Browse files Browse the repository at this point in the history
  • Loading branch information
dabico committed Sep 21, 2023
2 parents 8a67fa9 + 12ff5b7 commit 30f39b2
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/main/java/ch/usi/si/seart/treesitter/Point.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import lombok.Generated;
import lombok.Getter;
import lombok.experimental.FieldDefaults;
import org.jetbrains.annotations.NotNull;

/**
* Represents a two-dimensional point with row and column coordinates.
Expand All @@ -22,7 +23,7 @@
@AllArgsConstructor
@EqualsAndHashCode
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
public class Point {
public class Point implements Comparable<Point> {

private static final Point ORIGIN = new Point(0, 0);

Expand Down Expand Up @@ -53,6 +54,20 @@ public String toString() {
public boolean isOrigin() {
return equals(ORIGIN);
}

/* Compares this point with another point for positional order.
* Points are compared by their row coordinates first,
* and if those are equal they are then compared by their column coordinates.
*
* @param other the object to be compared
* @return the row comparison result, or the column comparison result if the rows are equal
* @since 1.5.1
*/
@Override
public int compareTo(@NotNull Point other) {
int comparison = Integer.compare(this.row, other.row);
return comparison != 0 ? comparison : Integer.compare(this.column, other.column);
}

/**
* Adds another point to this point,
Expand Down
15 changes: 15 additions & 0 deletions src/test/java/ch/usi/si/seart/treesitter/PointTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;

class PointTest {
Expand All @@ -23,6 +26,18 @@ void testIsOrigin() {
void testIsNotOrigin(Point point) {
Assertions.assertFalse(point.isOrigin());
}

@Test
void testCompareTo() {
List<Point> sorted = List.of(
new Point(0, 0), new Point(0, 1),
new Point(1, 0), new Point(1, 1)
);
ArrayList<Point> unsorted = new ArrayList<>(sorted);
Collections.shuffle(unsorted);
Collections.sort(unsorted);
Assertions.assertEquals(sorted, unsorted);
}

@Test
void testAdd() {
Expand Down

0 comments on commit 30f39b2

Please sign in to comment.