Skip to content

Instantly share code, notes, and snippets.

@cedced19
Last active May 25, 2017 17:51
Show Gist options
  • Save cedced19/9842197cdde54dcb69c8832bad5eb3c2 to your computer and use it in GitHub Desktop.
Save cedced19/9842197cdde54dcb69c8832bad5eb3c2 to your computer and use it in GitHub Desktop.
Get the distance between points
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
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