I got some problem on working with shunting yards algorithm : I use it to parse an equation then use that equation to draw an graph, but somehow it’s parsing x^2-0.5x+1 to -0.5x+1, is there anyways to fix that
Here the link to the test code : https://codepen.io/Inasaya-Flanderin/pen/ExbbgQm
This is the code part:
function parse(rpn) {
let stack = [];
Array.from(rpn).forEach((t) => {
let tr = null;
if (isNumber(t) || isVariable(t)) {
tr = genNode(t, false);
} else {
if (Object.keys(binary_functions).includes(t)) {
tr = genNode(binary_functions[t], true, false);
let a = stack.pop();
let b = stack.pop();
if (typeof a === 'number') {
tr.right = genNode(a, false);
} else {
tr.right = a;
}
if (typeof b === 'number') {
tr.left = genNode(b, false);
} else {
tr.left = b;
}
} else if (Object.keys(unary_functions).includes(t)) {
tr = genNode(unary_functions[t]);
a = stack.pop();
if (typeof a === 'number') {
tr.left = genNode(a, false);
} else {
tr.left = a;
}
}
}
tr.name = t;
stack.push(tr);
});
return stack.pop();
}
function eval(tree) {
if (tree.func) {
if (tree.unary) {
return tree.val.eval(eval(tree.left));
} else {
return tree.val.eval(eval(tree.left), eval(tree.right));
}
} else {
if (constant_names.includes(tree.val)) {
return constants[tree.val];
} else if (varnames.includes(tree.val)) {
return variables[tree.val];
} else {
return tree.val;
}
}
}