30-seconds-of-code: Alternative To Distance

Created on 23 Feb 2019  路  5Comments  路  Source: 30-seconds/30-seconds-of-code

Description

I noticed that you have code snippet for calculating the distance between two co-ordinates in 2d space. Would it be useful to add a code snippet which does the same but isn't confined to 2d space.

Most helpful comment

Sweet I will do pull request

All 5 comments

You could generalize it and make it x dimensional...

This what I have come up with so far:

function distance(...coords){
    let length = Math.trunc(coords.length/2);
    let sum = coords.slice(0,length).reduce((accumulator,currentValue,currentIndex) => accumulator + (Math.pow(currentValue-coords[length+currentIndex],2)),0);
    return Math.sqrt(sum);
}

// (10,0,10) & (2000,10,10)
console.log(distanceV2(10,0,10,2000,10,10)) //1990.0251254695254

Essentially:
1) The function can take any number of args (coords)
1) coords is split into half, separating the two points
1) For each co-ordinate component I find the difference between the two points and square
1) Finally I square root the sum

I was wondering what you think?

I like the idea, but it shouldn't be called distance. distance is the existing, simplified 2D version. Should we call it vectorDistance to make sure it's understandable?

Sweet I will do pull request

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for any follow-up tasks.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kingdavidmartins picture kingdavidmartins  路  5Comments

Chalarangelo picture Chalarangelo  路  5Comments

henrycjchen picture henrycjchen  路  4Comments

Speuta picture Speuta  路  3Comments

Priyansh2001here picture Priyansh2001here  路  5Comments