From 1076c3c7276cb3880fff3779fd43dd28fec14fd0 Mon Sep 17 00:00:00 2001 From: Glen Whitney Date: Sun, 31 Jul 2022 21:26:16 -0700 Subject: [PATCH] feat: add built-in typeOf operator to PocomathInstance --- src/core/PocomathInstance.mjs | 13 ++++++++++++- test/_pocomath.mjs | 9 +++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/core/PocomathInstance.mjs b/src/core/PocomathInstance.mjs index ba502d0..72bfc20 100644 --- a/src/core/PocomathInstance.mjs +++ b/src/core/PocomathInstance.mjs @@ -26,6 +26,7 @@ export default class PocomathInstance { 'install', 'installType', 'name', + 'typeOf', 'Types', 'undefinedTypes' ]) @@ -153,7 +154,13 @@ export default class PocomathInstance { if (type === 'any' || this._templateParam(type)) continue this.installType(type, spec) } - this._installFunctions(other._imps) + const migrateImps = {} + for (const operator in other._imps) { + if (operator != 'typeOf') { // skip the builtin, we already have it + migrateImps[operator] = other._imps[operator] + } + } + this._installFunctions(migrateImps) } /** @@ -305,6 +312,10 @@ export default class PocomathInstance { // rebundle anything that uses the new type: this._invalidateDependents(':' + type) + // update the typeOf function + const imp = {} + imp[type] = {uses: new Set(), does: () => () => type} + this._installFunctions({typeOf: imp}) } /* Returns a list of all types that have been mentioned in the diff --git a/test/_pocomath.mjs b/test/_pocomath.mjs index 8e88668..3e9f0a0 100644 --- a/test/_pocomath.mjs +++ b/test/_pocomath.mjs @@ -10,6 +10,15 @@ describe('The default full pocomath instance "math"', () => { assert.strictEqual(undef.length, 0) }) + it('has a built-in typeOf operator', () => { + assert.strictEqual(math.typeOf(42), 'NumInt') + assert.strictEqual(math.typeOf(-1.5), 'number') + assert.strictEqual(math.typeOf(-42n), 'bigint') + assert.strictEqual(math.typeOf(undefined), 'undefined') + assert.strictEqual(math.typeOf({re: 15n, im: -2n}), 'GaussianInteger') + assert.strictEqual(math.typeOf({re: 6.28, im: 2.72}), 'Complex') + }) + it('can subtract numbers', () => { assert.strictEqual(math.subtract(12, 5), 7) })