formula.js 1.1 KB

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