diff --git a/src/operator.js b/src/operator.js index 0c41d7eb..55285ee1 100644 --- a/src/operator.js +++ b/src/operator.js @@ -166,3 +166,7 @@ export function defineVectorLength(VectorClass, value) { Object.defineProperty(Vector, VECTOR_LENGTH, { value }); } + +export function cachedFactory(VectorClass) { + return bindCache((...args) => new VectorClass(...args)); +} diff --git a/test/operator.js b/test/operator.js index 518eb6c1..35f16976 100644 --- a/test/operator.js +++ b/test/operator.js @@ -1,26 +1,43 @@ -// @ts-nocheck import { assert } from 'chai'; -import { operatorCalc } from '../src/operator'; -import { Victor, Vector } from '../src'; +import { operatorCalc, cachedFactory } from '../src/operator'; +import { victor, vector } from '../src'; describe('operatorCalc with Victor test.', () => { it('should throw error with assgined Victor', () => { - const pos = new Victor(5, 6, 7); - const dir = new Victor(1, 0, 0); + const pos = victor(5, 6, 7); + const dir = victor(1, 0, 0); - assert.throws(() => operatorCalc(() => dir * pos, new Victor(1, 0, 0)), Error); + assert.throws(() => operatorCalc(() => dir * pos, victor(1, 0, 0)), Error); }); }); describe('operatorCalc with Vector test.', () => { it('should throw error with assgined Victor', () => { - const pos = new Vector(5, 6, 7); - const dir = new Vector(1, 0, 0); + const pos = vector(5, 6, 7); + const dir = vector(1, 0, 0); - const scale = operatorCalc(() => dir * pos, new Vector(1, 0.9, 0)); + const scale = operatorCalc(() => dir * pos, vector(1, 0.9, 0)); assert.equal(scale.x, 5); assert.equal(scale.y, 0); assert.equal(scale.z, 0); }); }); + +describe('operatorCalc with class using cachedFactory (Vector or Victor or Point or Ipoint) test.', () => { + let counter = 0; + class V { + constructor() { + counter++; + } + } + const vFactory = cachedFactory(V); + + it('factory call should be cached', () => { + const pos = vector(5, 6, 7); + const dir = vector(1, 0, 0); + operatorCalc(() => dir * vFactory() + 1); + + assert.equal(counter, 1); + }); +});