2
0

formula.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**
  2. * 公式编译
  3. */
  4. class Formula {
  5. private formula = "";
  6. private watchers: string[] = [];
  7. private ast: string[] = [];
  8. constructor(_formula) {
  9. this.formula = _formula;
  10. this.compile();
  11. }
  12. private compile() {
  13. // eslint-disable-next-line no-useless-escape
  14. const ast = this.formula.split(/([\+\-\*\/\(\)])/);
  15. this.ast = ast.filter((it) => it !== "");
  16. this.ast.forEach((char) => {
  17. if (this.isSymbol(char) || this.isStatic(char)) {
  18. return;
  19. }
  20. this.watchers.push(char.split(/[\.\[]/)[0]);
  21. });
  22. }
  23. private isSymbol(char: string) {
  24. return /^[\+\-\*\/\(\)]{1}$/g.test(char);
  25. }
  26. private isStatic(char: string) {
  27. return /[\"\']/.test(char) || /^\d+$/.test(char);
  28. }
  29. shouldUpdate(watcher: string) {
  30. return this.watchers.includes(watcher);
  31. }
  32. result(_context: NonNullable<unknown>) {
  33. const ast = this.ast.map((char) => {
  34. if (this.isSymbol(char) || this.isStatic(char)) {
  35. return char;
  36. }
  37. return char.replace(/(^[\.\[]*)/, "_context.$1");
  38. });
  39. return eval(ast.join(""));
  40. }
  41. destroy() {
  42. this.formula = "";
  43. this.watchers = [];
  44. this.ast = [];
  45. }
  46. }
  47. export { Formula };