17
snippets/vectorDistance.md
Normal file
17
snippets/vectorDistance.md
Normal 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
|
||||||
|
```
|
||||||
@ -332,6 +332,7 @@ URLJoin:string,utility,regexp,advanced
|
|||||||
UUIDGeneratorBrowser:browser,utility,random,intermediate
|
UUIDGeneratorBrowser:browser,utility,random,intermediate
|
||||||
UUIDGeneratorNode:node,utility,random,intermediate
|
UUIDGeneratorNode:node,utility,random,intermediate
|
||||||
validateNumber:utility,math,intermediate
|
validateNumber:utility,math,intermediate
|
||||||
|
vectorDistance:math,beginner
|
||||||
when:function,intermediate
|
when:function,intermediate
|
||||||
without:array,beginner
|
without:array,beginner
|
||||||
words:string,regexp,intermediate
|
words:string,regexp,intermediate
|
||||||
|
|||||||
9
test/vectorDistance.test.js
Normal file
9
test/vectorDistance.test.js
Normal 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);
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user