diff --git a/snippets/vectorDistance.md b/snippets/vectorDistance.md new file mode 100644 index 000000000..db3261dcb --- /dev/null +++ b/snippets/vectorDistance.md @@ -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 +``` diff --git a/tag_database b/tag_database index 785aa026e..7d248af61 100644 --- a/tag_database +++ b/tag_database @@ -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 diff --git a/test/vectorDistance.test.js b/test/vectorDistance.test.js new file mode 100644 index 000000000..746eb645e --- /dev/null +++ b/test/vectorDistance.test.js @@ -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); +});