Skip to content

Instantly share code, notes, and snippets.

@gf3
Created December 11, 2011 21:01
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 gf3/1462723 to your computer and use it in GitHub Desktop.
Save gf3/1462723 to your computer and use it in GitHub Desktop.
# Find closest point to a set of points.
findClosestPoint = (needle, haystack) ->
(init = new Point).diff = Number.MAX_VALUE
comparator = (memo, point) ->
point.diff = Math.abs(needle.x - point.x) + Math.abs(needle.y - point.y)
if point.diff < memo.diff then point else memo
_.foldl haystack, comparator, init
# Find closest point to a set of points based on angles.
findClosestPointByAngle = (needle, haystack, origin) ->
(init = new Point).diff = Number.MAX_VALUE
needle_angle = Point.angleForCircle origin, needle
comparator = (memo, point) ->
point.diff = Math.abs Point.angleForCircle(origin, point) - needle_angle
if point.diff < memo.diff then point else memo
_.foldl haystack, comparator, init
# Find closest point to a set of points based on angles *and* co-ords.
findClosestPointByAngleAndCoords = (needle, haystack, origin) ->
(init = new Point).diff = Number.MAX_VALUE
needle_angle = Point.angleForCircle origin, needle
comparator = (memo, point) ->
point.diff = (Math.abs Point.angleForCircle(origin, point) - needle_angle) + Math.abs(needle.x - point.x) + Math.abs(needle.y - point.y)
if point.diff < memo.diff then point else memo
_.foldl haystack, comparator, init
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment