From cfb13f28121bface58781128b9fa430a178846ed Mon Sep 17 00:00:00 2001 From: buzz-lightsnack-2007 <73412182+buzz-lightsnack-2007@users.noreply.github.com> Date: Mon, 22 Jul 2024 20:39:22 +0800 Subject: [PATCH] add completed interpreter.js --- interpreter.js | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 interpreter.js diff --git a/interpreter.js b/interpreter.js new file mode 100644 index 0000000..2e2900e --- /dev/null +++ b/interpreter.js @@ -0,0 +1,50 @@ +class Calculator { + result; + expression; + + /* + Perform a calculation. + + @param {string} expr the expression to solve + @return {Object} the result + */ + calculate(expr) { + try { + this.result = eval(expr); + } catch(err) { + alert(err); + }; + }; + + interactive() { + while (true) { + this.input = ``; + + this.input = (this.result != null) ? prompt(this.result) : prompt(); + + // Determine whether the user typed a value. + if ((this.input) ? this.input.trim() : false) { + this.expression = this.input.trim(); + delete this.input; + + // Solve the expression. + this.calculate(this.expression); + } else { + break; + } + } + } + + constructor() { + }; +}; + + +function main() { + let INSTANCE = new Calculator(); + INSTANCE.interactive(); +}; + +main(); + +