JSFiddle - React, Tailwind, and code Playground
by xavierm02
HTML
<input type="text" id="input" />
<div id="div"></div>
JavaScript
function toInt(x) {
return parseInt(x, 10);
}
function whileReplace(expr, reg, f) {
var oldExpr = null;
while (expr != oldExpr) {
oldExpr = expr;
expr = expr.replace(reg, f);
}
return expr;
}
function simpleCompute(expr) {
expr = whileReplace(expr, /\(([^\(\)]+)\)/g, function (s, x) {
return simpleCompute(x)
});
expr = whileReplace(expr, /([^+*\^\!])!/, function (s, x) {
var i = toInt(x);
if (i === 0) {
return 1
};
var r = i;
while (--i) {
r *= i;
}
return r;
});
expr = whileReplace(expr, /([^+*\^]+)\^([^+*\^]+)/, function (s, x, y) {
return Math.pow(toInt(x), toInt(y));
});
expr = whileReplace(expr, /([^+*]+)\*([^+*]+)/, function (s, x, y) {
return toInt(x) * toInt(y);
});
expr = whileReplace(expr, /([^+]+)\+([^+]+)/, function (s, x, y) {
return toInt(x) + toInt(y);
});
return expr;
}
var div = document.getElementById('div');
var input = document.getElementById('input');
input.value = "1*2+3*(4+5)+6";
input.onchange = function () {
var expr = this.value;
var test;
try {
test = eval(expr);
} catch (e) {
test = "?";
}
var str = test + " = " + expr + " = " + simpleCompute(expr);
div.innerHTML = str;
console.log(str);
}
input.onchange();