Skip to content

Instantly share code, notes, and snippets.

@w8r
Created January 12, 2017 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save w8r/4bf1715bddb42c3390d5b2430874c788 to your computer and use it in GitHub Desktop.
Save w8r/4bf1715bddb42c3390d5b2430874c788 to your computer and use it in GitHub Desktop.
Circle Sort Comparator
/**
* This is a comparator for two points to position them along the circle around C(x,y)
*
* @example
* points.sort(function (a, b) {
* return comparator(a.x, a.y, bx, b.y, c.x, c.y);
* });
*
* @param {number} ax
* @param {number} ay
* @param {number} bx
* @param {number} by
* @param {number} cx Center x
* @param {number} cy Center y
* @return {number} -1 if a is before b on the circle
*/
function compare (ax, ay, bx, by, cx, cy) {
if (ax - cx >= 0 && bx - cx < 0) return 1;
if (ax - cx < 0 && bx - cx >= 0) return -1;
if (ax - cx === 0 && bx - cx === 0) {
return (ay - by >= 0 || by - cy >= 0) ? (ay - by) : (by - ay);
}
// compute the cross product of vectors (center -> a) x (center -> b)
var det = (ax - cx) * (by - cy) - (bx - cx) * (ay - cy);
if (det < 0) return 1;
if (det > 0) return -1;
// points a and b are on the same line from the center
// check which point is closer to the center
var d1 = (ax - cx) * (ax - cx) + (ay - cy) * (ay - cy);
var d2 = (bx - cx) * (bx - cx) + (by - cy) * (by - cy);
return d1 - d2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment