Skip to content

Commit 890bb52

Browse files
committed
feat(vector): swizzle function
1 parent f12c190 commit 890bb52

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

src/index.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import formatNumber from './formatter';
88
const X = 0;
99
const Y = 1;
1010
const Z = 2;
11-
const AXES = Symbol.for('axes');
11+
const AXES = Symbol('axes');
1212

1313
function square(val) {
1414
return val * val;
@@ -175,6 +175,11 @@ class AVector {
175175
return [this.x, this.y, this.z];
176176
}
177177

178+
swizzle(target) {
179+
const data = target.split('').map(t => this[t]);
180+
return new this.constructor(data[0], data[1], data[2]);
181+
}
182+
178183
/**
179184
*
180185
* @throws NotImplementedError

test/index.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,13 @@ const vectorTest = (Vec3) => {
132132
assert.closeTo(cross3.y, 0, 0.01);
133133
assert.closeTo(cross3.z, 49, 0.01);
134134
});
135+
136+
it('should swizzle x y z values', () => {
137+
const pos = new Vec3(5, 6, 7).swizzle('zxy');
138+
assert.equal(pos.x, 7);
139+
assert.equal(pos.y, 5);
140+
assert.equal(pos.z, 6);
141+
});
135142
};
136143

137144
describe('standard Vector test.', () => {
@@ -184,3 +191,31 @@ describe('calc test.', () => {
184191
assert.equal(vec, 7);
185192
});
186193
});
194+
195+
describe('performance test', () => {
196+
it('should be fast', () => {
197+
let time = new Date().getTime();
198+
199+
const v1 = new Vector(1, 2, 3);
200+
const v2 = new Vector(4, 5, 6);
201+
for (let i = 0; i < 10000; i++) {
202+
const v3 = calc(() => v1.cross(v2) + v2 * v1 - v1 / v2 + (v2 * v2) / v1);
203+
}
204+
time = new Date().getTime() - time;
205+
console.log('perf test fast', `${Math.round(time) / 1000}s`);
206+
});
207+
208+
it('should be faster', () => {
209+
let time = new Date().getTime();
210+
211+
const v1 = new Vector(1, 2, 3);
212+
const v2 = new Vector(4, 5, 6);
213+
214+
const fn = () => v1 + v2 * v1 - v1 / v2 + (v2 * v2) / v1;
215+
for (let i = 0; i < 10000; i++) {
216+
const v3 = calc(fn);
217+
}
218+
time = new Date().getTime() - time;
219+
console.log('perf test faster', `${Math.round(time) / 1000}s`);
220+
});
221+
});

0 commit comments

Comments
 (0)