MCPcopy Create free account
hub / github.com/SiddhantSilwal/RaspberryPi-GPIO-Web-Controller / MathParser

Class MathParser

AppData/static/js/graph.js:7–89  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

5
6 // Secure Math Parser (No Eval)
7 class MathParser {
8 constructor(str) {
9 this.tokens = this.tokenize(str);
10 this.pos = 0;
11 }
12 tokenize(str) {
13 return (
14 str
15 .replace(/\s+/g, "")
16 .match(/([0-9]*\.?[0-9]+|[a-z]+|[+\-*/^()]|x)/gi) || []
17 );
18 }
19 consume() {
20 return this.tokens[this.pos++];
21 }
22 peek() {
23 return this.tokens[this.pos];
24 }
25 parseExpression() {
26 let node = this.parseTerm();
27 while (this.peek() === "+" || this.peek() === "-") {
28 const op = this.consume();
29 const right = this.parseTerm();
30 const left = node;
31 node = (x) =>
32 op === "+" ? left(x) + right(x) : left(x) - right(x);
33 }
34 return node;
35 }
36 parseTerm() {
37 let node = this.parsePower();
38 while (this.peek() === "*" || this.peek() === "/") {
39 const op = this.consume();
40 const right = this.parsePower();
41 const left = node;
42 node = (x) => {
43 const r = right(x);
44 return op === "*" ? left(x) * r : r === 0 ? NaN : left(x) / r;
45 };
46 }
47 return node;
48 }
49 parsePower() {
50 let node = this.parseFactor();
51 while (this.peek() === "^") {
52 this.consume();
53 const right = this.parseFactor();
54 const left = node;
55 node = (x) => Math.pow(left(x), right(x));
56 }
57 return node;
58 }
59 parseFactor() {
60 const token = this.consume();
61 if (token === "(") {
62 const node = this.parseExpression();
63 this.consume();
64 return node;

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected