diff --git a/src/index.js b/src/index.js index 5e568613..22159fd9 100644 --- a/src/index.js +++ b/src/index.js @@ -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; @@ -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 diff --git a/test/index.js b/test/index.js index d4cb6e0d..f833c1ab 100644 --- a/test/index.js +++ b/test/index.js @@ -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.', () => { @@ -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`); + }); +});