Skip to content

Commit 8ff17b6

Browse files
committed
Don't mutate the vector during calculation of euclidian distance
1 parent 3f8dcf8 commit 8ff17b6

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

index.coffee

+8-3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
calculateLength = (x, y, z) -> Math.sqrt (x * x) + (y * y) + (z * z)
2+
13
class Vector
24
constructor: (@x = 0, @y = 0, @z = 0) ->
35
@isNormalized = undefined
@@ -56,11 +58,14 @@ class Vector
5658

5759
return @
5860

59-
length: () ->
60-
return Math.sqrt (@x * @x) + (@y * @y) + (@z * @z)
61+
length: () -> calculateLength @x, @y, @z
6162

6263
euclideanDistanceTo: (vector) ->
63-
return @subtract(vector).length()
64+
return calculateLength(
65+
@x - vector.x
66+
@y - vector.y
67+
@z - vector.z
68+
)
6469

6570
normalize: () ->
6671
@isNormalized = true

test/main.coffee

+2
Original file line numberDiff line numberDiff line change
@@ -75,9 +75,11 @@ runTest 'Returns a vector\'s length', (test) ->
7575

7676
runTest 'Returns the euclidian distance to a vector', (test) ->
7777
vectorA = new Vector(4, 2, 0)
78+
vectorAReference = vectorA.clone()
7879
vectorB = new Vector(3, 5, 7)
7980
expectedDistance = 7.681145747868608
8081
test.same(vectorA.euclideanDistanceTo(vectorB), expectedDistance)
82+
test.same(vectorA, vectorAReference)
8183

8284

8385
runTest 'Normalizes a vector', (test) ->

0 commit comments

Comments
 (0)