Skip to content

Commit

Permalink
feat(vector): optimize code for caching getter
Browse files Browse the repository at this point in the history
  • Loading branch information
MrTelanie committed Aug 22, 2018
1 parent a70e937 commit 844bf05
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ function dot(one, two) {
return one.x * two.x + one.y * two.y + one.z * two.z;
}

function getLength(v) {
return Math.sqrt(dot(v, v));
}

class AVector {
constructor(x, y, z) {
if (typeof x === 'function') {
Expand All @@ -36,11 +40,11 @@ class AVector {
}

valueOf() {
return this.length;
return getLength(this);
}

normalize() {
const { length } = this;
const length = getLength(this);
return this.createVector(this.x / length, this.y / length, this.z / length);
}

Expand All @@ -61,7 +65,7 @@ class AVector {

crossNormalize(v) {
const vec = cross(this, v);
const { length } = vec;
const length = getLength(vec);
vec[X] /= length;
vec[Y] /= length;
vec[Z] /= length;
Expand All @@ -75,12 +79,12 @@ class AVector {
toAngles() {
return {
theta: Math.atan2(this.z, this.x),
phi: Math.asin(this.y / this.length)
phi: Math.asin(this.y / getLength(this))
};
}

angleTo(a) {
return Math.acos(dot(this, a) / (this.length * a.length));
return Math.acos(dot(this, a) / (getLength(this) * getLength(a)));
}

// http://schteppe.github.io/cannon.js/docs/files/src_math_Quaternion.js.html
Expand Down Expand Up @@ -121,7 +125,7 @@ class AVector {
}

get length() {
return Math.sqrt(dot(this, this));
return getLength(this);
}

get len() {
Expand Down

0 comments on commit 844bf05

Please sign in to comment.