12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- class Formula {
- constructor(_formula) {
- this.formula = "";
- this.watchers = [];
- this.ast = [];
- this.formula = _formula;
- this.compile();
- }
- compile() {
- const ast = this.formula.split(/([\+\-\*\/\(\)])/);
- this.ast = ast.filter((it) => it !== "");
- this.ast.forEach((char) => {
- if (this.isSymbol(char) || this.isStatic(char)) {
- return;
- }
- this.watchers.push(char.split(/[\.\[]/)[0]);
- });
- }
- isSymbol(char) {
- return /^[\+\-\*\/\(\)]{1}$/g.test(char);
- }
- isStatic(char) {
- return /[\"\']/.test(char) || /^\d+$/.test(char);
- }
- shouldUpdate(watcher) {
- return this.watchers.includes(watcher);
- }
- result(_context) {
- const ast = this.ast.map((char) => {
- if (this.isSymbol(char) || this.isStatic(char)) {
- return char;
- }
- return char.replace(/(^[\.\[]*)/, "_context.$1");
- });
- return eval(ast.join(""));
- }
- destroy() {
- this.formula = "";
- this.watchers = [];
- this.ast = [];
- }
- }
- export { Formula };
|