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.
This commit is contained in:
Glen Whitney 2022-03-25 13:43:37 -07:00
parent 1c1ba91e48
commit 4213ade4ba
3 changed files with 14 additions and 1 deletions

View File

@ -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
}])
}

View File

@ -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
}

View File

@ -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))
})
})