add completed interpreter.js

This commit is contained in:
buzz-lightsnack-2007 2024-07-22 20:39:22 +08:00
parent f60da0d400
commit cfb13f2812

50
interpreter.js Normal file
View file

@ -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();