Skip to content

Commit

Permalink
feat(vector): swizzle function
Browse files Browse the repository at this point in the history
  • Loading branch information
MrTelanie committed Dec 14, 2018
1 parent f12c190 commit 890bb52
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import formatNumber from './formatter';
const X = 0;
const Y = 1;
const Z = 2;
const AXES = Symbol.for('axes');
const AXES = Symbol('axes');

function square(val) {
return val * val;
Expand Down Expand Up @@ -175,6 +175,11 @@ class AVector {
return [this.x, this.y, this.z];
}

swizzle(target) {
const data = target.split('').map(t => this[t]);
return new this.constructor(data[0], data[1], data[2]);
}

/**
*
* @throws NotImplementedError
Expand Down
35 changes: 35 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,13 @@ const vectorTest = (Vec3) => {
assert.closeTo(cross3.y, 0, 0.01);
assert.closeTo(cross3.z, 49, 0.01);
});

it('should swizzle x y z values', () => {
const pos = new Vec3(5, 6, 7).swizzle('zxy');
assert.equal(pos.x, 7);
assert.equal(pos.y, 5);
assert.equal(pos.z, 6);
});
};

describe('standard Vector test.', () => {
Expand Down Expand Up @@ -184,3 +191,31 @@ describe('calc test.', () => {
assert.equal(vec, 7);
});
});

describe('performance test', () => {
it('should be fast', () => {
let time = new Date().getTime();

const v1 = new Vector(1, 2, 3);
const v2 = new Vector(4, 5, 6);
for (let i = 0; i < 10000; i++) {
const v3 = calc(() => v1.cross(v2) + v2 * v1 - v1 / v2 + (v2 * v2) / v1);
}
time = new Date().getTime() - time;
console.log('perf test fast', `${Math.round(time) / 1000}s`);
});

it('should be faster', () => {
let time = new Date().getTime();

const v1 = new Vector(1, 2, 3);
const v2 = new Vector(4, 5, 6);

const fn = () => v1 + v2 * v1 - v1 / v2 + (v2 * v2) / v1;
for (let i = 0; i < 10000; i++) {
const v3 = calc(fn);
}
time = new Date().getTime() - time;
console.log('perf test faster', `${Math.round(time) / 1000}s`);
});
});

0 comments on commit 890bb52

Please sign in to comment.