UNPKG

nerdamer-ts

Version:

javascript light-weight symbolic math expression evaluator

117 lines 3.33 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.VariableDictionary = void 0; const Utils_1 = require("../Core/Utils"); class VariableDictionary { constructor() { this.vars = {}; this.constants = {}; this.reserved = []; } setVar(name, value) { this.vars[name] = value; } getVar(name) { return this.vars[name]; } isVar(name) { return name in this.vars; } deleteVar(name) { delete this.vars[name]; } clearAllVars() { this.vars = {}; } getAllVars() { return this.vars; } setConstant(name, value) { this.constants[name] = value; } getConstant(name) { return this.constants[name]; } isConstant(name) { return name in this.constants; } getAllConstants() { return this.constants; } deleteConstant(name) { delete this.constants[name]; } /** * Is used for u-substitution. Gets a suitable u for substitution. If for * instance a is used in the symbol then it keeps going down the line until * one is found that's not in use. If all letters are taken then it * starts appending numbers. * IMPORTANT! It assumes that the substitution will be undone * beore the user gets to interact with the object again. * @param {Symbol} symbol */ getU(symbol) { //start with u let u = 'u', //start with u v = u, //init with u c = 0, //postfix number vars = symbol.variables(); //make sure this variable isn't reserved and isn't in the variable list while (!(this.reserved.indexOf(v) === -1 && vars.indexOf(v) === -1)) { v = u + c++; } //get an empty slot. It seems easier to just push but the //problem is that we may have some which are created by clearU for (let i = 0, l = this.reserved.length; i <= l; i++) { //reserved cannot equals false or 0 so we can safely check for a falsy type if (!this.reserved[i]) { this.reserved[i] = v; //reserve the variable break; } } return v; } /** * Clears the u variable so it's no longer reserved * @param {String} u */ clearU(u) { let idx = this.reserved.indexOf(u); if (idx !== -1) { this.reserved[idx] = undefined; } } ; /** * Checks to see if value is one of nerdamer's reserved names * @param {String} name * @return boolean */ isReserved(name) { return this.reserved.indexOf(name) !== -1; } reserveName(name) { if (!this.isReserved(name)) { this.reserved.push(name); } } /** * Reserves the names in an object so they cannot be used as function names * @param {Object} obj */ reserveNames(obj) { if (typeof obj === 'string') { this.reserveName(obj); } else { (0, Utils_1.each)(obj, (x) => { this.reserveName(String(x)); }); } } getReserved() { return this.reserved; } } exports.VariableDictionary = VariableDictionary; //# sourceMappingURL=VariableDictionary.js.map