Math behind a Javascript implementation of shortest vector distance

483 Views Asked by At

I got a implementation of finding the shortest vector distance, but would like to know the actual equation for this implementation.

function closestLocation(targetLocation, locationData){


    function vectorDistance(dx, dy){
        return Math.sqrt(dx * dx + dy * dy);
    }

    function locationDistance(location1, location2){
        var dx = location1.latitude - location2.latitude,
            dy = location1.latitude - location2.longitude;

        return vectorDistance(dx, dy);
    }

    return locationData.reduce(function(prev, curr){
        var prevDistance = locationDistance(targetLocation, prev),
            currDistance = locationDistance(targetLocation, curr);

        return (prevDistance < currDistance) ? prev : curr;
    });

}

Any that can help with that?

1

There are 1 best solutions below

1
On BEST ANSWER

So basically if you have two points in 2D space

$p_1=\left(x_1,y_1\right)$ and $p_2=\left(x_2,y_2\right)$.

Its distance, as calculated in this Java code, is the Euclidean distance

$d=\sqrt{\left(x_1-x_2\right)^2+\left(y_1-y_2\right)^2}$

In parts, the function locationDistance computes the parts inside the parenthesis in the square root and the function vectorDistance computes d.

It is not clear from your piece of code but I suspect that the variables prev and curr will be part of a loop that tries to compare a given location (targetLocation) with a set of other locations (locationData) and keep always the minimum in prev comparing with the new ones in curr. And that's what is done in the reduce statement.