Skip to content

Commit aa1e1ae

Browse files
Added Euclidean Distance
1 parent 0ca18c2 commit aa1e1ae

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

Maths/EuclideanDistance.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// Wikipedia: https://en.wikipedia.org/wiki/Euclidean_distance
2+
3+
const EuclideanDistance = (vector1, vector2) => {
4+
let sumOfSquares = 0
5+
6+
for (let i = 0; i < vector1.length; i++) {
7+
sumOfSquares += Math.pow(vector1[i] - vector2[i], 2)
8+
}
9+
10+
return Math.sqrt(sumOfSquares)
11+
}
12+
13+
export { EuclideanDistance }

Maths/test/EuclideanDistance.test.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { EuclideanDistance } from '../EuclideanDistance.js'
2+
3+
describe('EuclideanDistance', () => {
4+
it('should calculate the distance correctly for 2D vectors', () => {
5+
expect(EuclideanDistance([0, 0], [2, 2])).toBeCloseTo(2.8284271247461903, 10)
6+
})
7+
8+
it('should calculate the distance correctly for 3D vectors', () => {
9+
expect(EuclideanDistance([0, 0, 0], [2, 2, 2])).toBeCloseTo(3.4641016151377544, 10)
10+
})
11+
12+
it('should calculate the distance correctly for 4D vectors', () => {
13+
expect(EuclideanDistance([1, 2, 3, 4], [5, 6, 7, 8])).toBeCloseTo(8.0, 10)
14+
})
15+
16+
it('should calculate the distance correctly for different 2D vectors', () => {
17+
expect(EuclideanDistance([1, 2], [4, 6])).toBeCloseTo(5.0, 10)
18+
})
19+
})

0 commit comments

Comments
 (0)