Last active
February 16, 2018 16:43
-
-
Save dijonkitchen/ddd3b69368df4e8cdc5b9f5d9bc0974d to your computer and use it in GitHub Desktop.
Calculate nearest 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
const distance = (point1, point2) => { | |
return Math.sqrt(Math.pow(point2[0] - point1[0], 2) + Math.pow(point2[1] - point1[1],2)) | |
} | |
const nearestPoints = (basePoint, pointList, numberOfNearestWanted) => { | |
const pointDistances = pointList.map(point => { | |
return { | |
point, | |
distance: distance(basePoint, point) | |
} | |
}) | |
pointDistances.sort((prevPoint, nextPoint) => prevPoint.distance - nextPoint.distance) | |
return pointDistances.slice(0, numberOfNearestWanted) | |
} | |
// Tests | |
const point1 = [0,0] | |
const point2 = [0,1] | |
console.log(distance(point1, point2)) // 1 | |
const points = [point1, point2, [4,6], [12,32]] | |
console.log(nearestPoints(point1, points, 2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment