Created
January 12, 2017 17:27
-
-
Save w8r/4bf1715bddb42c3390d5b2430874c788 to your computer and use it in GitHub Desktop.
Circle Sort Comparator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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