Reputation: 9866
I'm converting some code to JavaScript from Java, and I've come across this code:
static final Comparator<Point> compareXCoord = new Comparator<Point>() {
@Override
public int compare(Point o1, Point o2) {
return ComparisonChain.start().
compare(o1.x, o2.x).
compare(o1.y, o2.y).
result();
}
};
static final Comparator<Point> compareYCoord = new Comparator<Point>() {
@Override
public int compare(Point o1, Point o2) {
return ComparisonChain.start().
compare(o1.y, o2.y).
compare(o1.x, o2.x).result();
}
};
...
Arrays.binarySearch(ypoints, Point.make(Double.NEGATIVE_INFINITY, ymin),
compareYCoord);
Seems fair enough, as it'll return the resultant object of the matching comparison chain.
But what I don't understand is that both methods seem to my naive eyes to do the exact same thing: return if either the x
or y
properties match. The only difference is the first checks the x
property first, i.e., the order of the checks is different.
Also, if that's true, then the Arrays.binarySearch
method will return ypoints
elements with equal x
properties. I don't feel this is what the function is intended to do.
So, my JavaScript translation would be:
function compareXCoord(p1, p2) {
return (p1.x === p2.x) ? p1 :
(p1.y === p2.y) ? p1 : undefined;
}
function compareYCoord(p1, p2) {
return (p1.y === p2.y) ? p1 :
(p1.x === p2.x) ? p1 : undefined;
}
But both of these could be simplified to return (p1.y === p2.y || p1.x === p2.x) ? p1 : undefined;
.
I feel I'm certainly misunderstanding how ComparisonChain
works. Is the order of the chain important? Bonus points for directions into how to translate this to JavaScript.
Upvotes: 0
Views: 101
Reputation: 272647
You need to bear in mind that the Java Comparator
return value is three-valued (i.e. higher, lower, or equal). Thus the order in which you compare the coordinates is important - sorting by x
first is not the same as sorting by y
first.
Upvotes: 1