From 487884e09467dfb98e0b4ca7043069698b62a16b Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Mon, 28 Dec 2020 13:41:19 +0200 Subject: [PATCH] Add euclideanDistance --- snippets/euclideanDistance.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 snippets/euclideanDistance.md diff --git a/snippets/euclideanDistance.md b/snippets/euclideanDistance.md new file mode 100644 index 000000000..5ce5a39bc --- /dev/null +++ b/snippets/euclideanDistance.md @@ -0,0 +1,19 @@ +--- +title: euclideanDistance +tags: math,algorithm,intermediate +--- + +Calculates the distance between two points in any number of dimensions. + +- Use `Object.keys()` and `Array.prototype.map()` to map each coordinate to its difference between the two points. +- Use `Math.hypot()` to calculate the Euclidean distance between the two points. + +```js +const euclideanDistance = (a, b) => + Math.hypot(...Object.keys(a).map(k => b[k] - a[k])); +``` + +```js +euclideanDistance([1, 1], [2, 3]); // ~2.2361 +euclideanDistance([1, 1, 1], [2, 3, 2]); // ~2.4495 +```