From 4213ade4ba5bd010e497eac48f39bf254361e165 Mon Sep 17 00:00:00 2001 From: Glen Whitney Date: Fri, 25 Mar 2022 13:43:37 -0700 Subject: [PATCH] feat: Add a configuration for an instance that can be set at creation time And use it to control whether the result of a complex operation where the imaginary part comes out to 0 will be coerced back to a number. --- complex/add.js | 2 ++ picomathInstance.js | 3 ++- test/custom.js | 10 ++++++++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/complex/add.js b/complex/add.js index 1293a14..fc07a9c 100644 --- a/complex/add.js +++ b/complex/add.js @@ -2,6 +2,7 @@ import { anyComplex } from './complex.js' export default function create(pmath) { const complex = pmath('complex') + const resolve = pmath.config.resolveComplex return pmath('add', [anyComplex, // naive, but this is just a P-o-C (...addends) => { let sum = complex(addends[0]) @@ -10,6 +11,7 @@ export default function create(pmath) { sum.re += addend.re sum.im += addend.im } + if (resolve && Math.abs(sum.im/sum.re) < 1e-10) return sum.re return sum }]) } diff --git a/picomathInstance.js b/picomathInstance.js index 8bac098..759d215 100644 --- a/picomathInstance.js +++ b/picomathInstance.js @@ -1,7 +1,7 @@ /* Core of picomath: generates an instance */ import poortf from './poortf.js' -export default function picomathInstance (instName) { +export default function picomathInstance (instName, config) { /* Since we have to do it all the time, when we call a picomath instance * as a function, it takes a name and 0 or more implementations add adds * them to its poortf property named name, returning that property value. @@ -16,6 +16,7 @@ export default function picomathInstance (instName) { } Object.defineProperty(fn, 'name', {value: instName}) + fn.config = config || { resolveComplex: false } // primitive default for POC return fn } diff --git a/test/custom.js b/test/custom.js index c14e849..69ac993 100644 --- a/test/custom.js +++ b/test/custom.js @@ -36,4 +36,14 @@ describe('Custom instances', () => { assert.strictEqual('subtract' in cherry, false) assert.strictEqual('negate' in cherry, false) }) + + const res = picoInstance('resolving', { resolveComplex: true }) + createNumbers(res) + createComplex(res) + + it("can be configured", () => { + assert.strictEqual(res.add(res.complex(2,3), res.complex(2,-3)), 4) + assert.deepStrictEqual(math.add(math.complex(2,3), math.complex(2,-3)), + math.complex(4,0)) + }) })