Skip to content

Instantly share code, notes, and snippets.

@RJ-Infinity
Created August 26, 2026 08:23
Show Gist options
  • Select an option

  • Save RJ-Infinity/afc41eebb2f00446b6d291cde330cd42 to your computer and use it in GitHub Desktop.

Select an option

Save RJ-Infinity/afc41eebb2f00446b6d291cde330cd42 to your computer and use it in GitHub Desktop.
basic expresion execution
const token_precedence = {
"-": 1,
"+": 1,
"*": 2,
"/": 2,
"^": 3,
"n": 4,
"(": 5,
")": 5,
};
function parse_exp_to_rev_pol(exp) {
/// tokenise
const tokens = [];
for (let i = 0; i < exp.length; i++) {
if (exp[i] == "-" && (i == 0 || exp[i-1] < "0" || exp[i-1] > "9" || exp[i-1] == "(")) {
tokens.push("n");
}else if (exp[i] >= "0" && exp[i] <= "9") {
let number = "";
while (exp[i] >= "0" && exp[i] <= "9") {
number += exp[i];
i++;
}
i--;
tokens.push(Number(number));
} else {
tokens.push(exp[i]);
}
}
console.log(tokens);
const output = [];
const ops = [];
for (let i = 0; i < tokens.length; i++) {
if (typeof tokens[i] === "number") {
output.push(tokens[i]);
} else if (tokens[i] == "("){
ops.push(tokens[i]);
} else if (tokens[i] == ")"){
while (true) {
const top = ops.pop();
if (typeof top === "undefined") {
throw "Mismatched brackets";
}
if (top == "(") { break; }
output.push(top);
}
} else {
while (ops.length > 0 && ops.at(-1) != "(" && token_precedence[ops.at(-1)] > token_precedence[tokens[i]]) {
output.push(ops.pop());
}
ops.push(tokens[i]);
}
}
while (ops.length > 0){
const val = ops.pop();
if (val == "(") {
throw "Mismatched brackets";
}
output.push(val);
}
return output;
}
function compute_reverse_polish(tokens){
const val = tokens.pop();
if (typeof val === "number") {
return val;
}
if (val == "n") {
return -compute_reverse_polish(tokens);
} else if (val == "^") {
const rhs = compute_reverse_polish(tokens);
return compute_reverse_polish(tokens) ** rhs;
} else if (val == "/") {
const rhs = compute_reverse_polish(tokens);
return compute_reverse_polish(tokens) / rhs;
} else if (val == "*") {
const rhs = compute_reverse_polish(tokens);
return compute_reverse_polish(tokens) * rhs;
} else if (val == "+") {
const rhs = compute_reverse_polish(tokens);
return compute_reverse_polish(tokens) + rhs;
} else if (val == "-") {
const rhs = compute_reverse_polish(tokens);
return compute_reverse_polish(tokens) - rhs;
} else {
console.log(val)
throw "ERROR????"
}
}
function compute_exp(exp) {
const tokens = parse_exp_to_rev_pol(exp);
const result = compute_reverse_polish(tokens);
if (tokens.length > 0) {
throw "invalid expression";
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment