Last active
November 6, 2020 23:53
-
-
Save moltenform/1d4f7ae9a8c3080d7877eda7b9fc0566 to your computer and use it in GitHub Desktop.
A little parser 2. evaluating
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* evaluate a tree of results. */ | |
function evalResult(result) { | |
if (result.type === exps.NumOrGroup) { | |
/* ex: (123 + 456) */ | |
return evalResult(result.parts[0]); | |
} else if (result.type === exps.NumLiteral) { | |
/* from the string "123" into a number. */ | |
return parseFloat(result.parts[0]); | |
} else { | |
/* reduce/evaluate the expression */ | |
let [operator, ...exprs] = result.parts; | |
let val = evalResult(exprs[0]); | |
for (let i = 1; i < exprs.length; i++) { | |
if (operator === "+") { | |
val += evalResult(exprs[i]); | |
} else if (operator === "*") { | |
val *= evalResult(exprs[i]); | |
} else if (operator === "^") { | |
val = Math.pow(val, evalResult(exprs[i])); | |
} else { | |
throw new Error("Unknown operator."); | |
} | |
} | |
return val; | |
} | |
} | |
/* how to run and evaluate an expression */ | |
function demo() { | |
let got = evalResult(parseTotal(verySimpleLexer("2 + 3 * 4"))); | |
console.log(`2 + 3 * 4 = ${got}`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment