JSFiddle - React, Tailwind, and code Playground
HTML
<textarea id="input" name="Text1" cols="40" rows="5" placeholder="enter script here">
print "Euclidean algorithm"
a = 240
print "a = " a
b = 360
print "b = " b
if a > 0
while b
if a > b
a = a - b
else
b = b - a
end if
end while
print "gcd: " a
else
print "gcd: " b
end if
</textarea>
<input type="button" value="test" />
<textarea id="output" name="Text2" cols="40" rows="5" placeholder="output"></textarea>
<script id="my-script"></script>
CSS
textarea {
white-space:pre-wrap;
}
JavaScript
function escapeRegExp(s) {
return s.replace(/([.*+?^=!:${}()\]\[\/\\])/g, '\\$1');
}
function replaceAll(p) {
return p['string'].replace(new RegExp(escapeRegExp(p['search']), 'g'), p['replace']);
}
rxAssignment = new RegExp(/^ *([a-zA-Z]+) *=(.+)$/);
rxFormulaPart = new RegExp(/^ *([a-zA-Z]+|[0-9]+) *([-+*\/%]) *(.*)$/);
rxVariable = new RegExp(/^ *([a-zA-Z]+) *$/);
rxInt = new RegExp(/^ *([0-9]+) *$/);
rxPrint = new RegExp(/^ *print +"([^"]*)"( +([a-zA-Z]+))? *$/);
rxWhile = new RegExp(/^ *while +([a-zA-Z]+) *$/);
rxEndWhile = new RegExp(/^ *end +while *$/);
rxIf = new RegExp(/^ *if +([a-zA-Z]+) *([><=]) *([a-zA-Z]+|-?[0-9]+) *$/);
rxElse = new RegExp(/^ *else *$/);
rxEndIf = new RegExp(/^ *end +if *$/);
$('input[type=button]').click(function () {
var lines = $('#input').val().split("\n");
var s = "myProgram=function(){var variables=[];var pOut='';"; // script
for (var i = 0; i < lines.length; i++) {
if (lines[i].trim().length == 0) {
continue;
}
var t = lines[i].match(rxPrint);
if (t !== null) {
s += "pOut+='" + replaceAll({string: t[1], search: "'", replace: "\\'"}) + (typeof t[3] == 'undefined' ? "\\n'" : "'+variables['" + t[3] + "']+'\\n'") + ";";
continue;
}
t = lines[i].match(rxWhile);
if (t !== null) {
s += "while(variables['" + t[1] + "']){";
continue;
}
t = lines[i].match(rxEndWhile);
if (t !== null) {
s += "}";
continue;
}
t = lines[i].match(rxIf);
if (t !== null) {
var t2 = t[3].match(rxInt);
var q;
if (t2 === null) {
t2 = t[3].match(rxVariable);
q = "variables['" + t2[1] + "']";
} else {
q = t2[1];
}
s += "if(variables['" + t[1] + "']" + t[2] + q + "){";
continue;
}
t =...