Merge pull request #926 from YusofBandar/master

vectorDistance Snippet
This commit is contained in:
Angelos Chalaris
2019-02-25 08:31:42 +02:00
committed by GitHub
3 changed files with 27 additions and 0 deletions

View File

@ -0,0 +1,17 @@
### vectorDistance
Returns the distance between two vectors.
Use `Array.prototype.reduce()`, `Math.pow()` and `Math.sqrt()` to calculate the Euclidean distance between two vectors.
```js
const vectorDistance = (...coords) => {
let pointLength = Math.trunc(coords.length / 2);
let sum = coords.slice(0, pointLength).reduce((acc, val, i) => acc + (Math.pow(val - coords[pointLength + i], 2)), 0);
return Math.sqrt(sum);
};
```
```js
vectorDistance(10, 0, 5, 20, 0, 10); // 11.180339887498949
```

View File

@ -332,6 +332,7 @@ URLJoin:string,utility,regexp,advanced
UUIDGeneratorBrowser:browser,utility,random,intermediate
UUIDGeneratorNode:node,utility,random,intermediate
validateNumber:utility,math,intermediate
vectorDistance:math,beginner
when:function,intermediate
without:array,beginner
words:string,regexp,intermediate

View File

@ -0,0 +1,9 @@
const expect = require('expect');
const { vectorDistance } = require('./_30s.js');
test('vectorDistance is a Function', () => {
expect(vectorDistance).toBeInstanceOf(Function);
});
test('Calculates the distance between two vectors', () => {
expect(distance(10, 0, 5, 20, 0, 10)).toBeCloseTo(11.180339887498949, 5);
});