Last active
May 25, 2017 17:51
-
-
Save cedced19/9842197cdde54dcb69c8832bad5eb3c2 to your computer and use it in GitHub Desktop.
Get the distance between points
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
var points = [ | |
{x: 4, y: 3}, | |
{x: 5, y: 2}, | |
{x: 6, y: 1}, | |
{x: 7, y: 0}, | |
{x: 8, y: -1}, | |
{x: 8, y: 9}, | |
{x: 1, y: 1}, | |
{x: 9, y: -4} | |
]; | |
var currentPosition = {x: 0, y: 0}; | |
function distanceBtwPoint (position, reference) { | |
return Math.sqrt(Math.pow((position.x-reference.x),2)+Math.pow((position.y-reference.y),2)) | |
} | |
function getNearestPosition (currentPosition, points) { | |
var lowestDistance = null; | |
var nearestPosition; | |
points.forEach(function (point, key) { | |
var distance = distanceBtwPoint(currentPosition, point); | |
if (lowestDistance === null || lowestDistance > distance) { | |
lowestDistance = distance; | |
nearestPosition = key; | |
} | |
}); | |
return nearestPosition; | |
}; | |
getNearestPosition(currentPosition, points); // Should display 6 |
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
function distance (position, reference) { | |
return Math.sqrt(Math.pow((position.x-reference.x),2)+Math.pow((position.y-reference.y),2)) | |
} | |
distance({x: 0, y: 0}, {x: 3, y: 4}); // Should return 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment