hexat/Hexat.hx

97 lines
2 KiB
Haxe
Raw Permalink Normal View History

2025-01-05 02:43:36 +00:00
import js.Browser.document;
import js.html.TextAreaElement;
enum Token {
Operation(op:String);
Number(num:Int);
}
2025-01-05 02:45:56 +00:00
class Hexat {
2025-01-05 02:43:36 +00:00
static public function main() {
var button = document.querySelector(".runButton");
button.onclick = (event) -> runButton();
}
static public function runButton() {
var inputArea:TextAreaElement = cast document.querySelector(".source");
var res = run(parse(inputArea.value));
var outputDisplay = document.querySelector(".output");
outputDisplay.innerHTML = "Output: <pre>"+res.join(", ")+"</pre>";
}
static function parse(input:String) {
var array: Array<Token> = [];
var i = 0;
var splits = input.split(" ");
while (i < splits.length) {
var split = splits[i];
if(split != " " && split != "\n" && split != "\r") {
if(Std.parseInt(split) != null) {
var num = Std.parseInt(split);
array.push(Number(num));
} else if (["+", "-", "*", "/", "@"].contains(split)) {
array.push(Operation(split));
}
}
i++;
}
return array;
}
static function run(array:Array<Token>) {
var stack: Array<Int> = [];
var i = 0;
while (i < array.length) {
if(array[i].getName() == "Number") {
stack.push(array[i].getParameters()[0]);
} else if (array[i].getName() == "Operation") {
var op = array[i].getParameters()[0];
switch (op) {
case "+":
var right = stack.pop();
var left = stack.pop();
var res = left + right;
stack.push(res);
case "-":
var right = stack.pop();
var left = stack.pop();
var res = left - right;
stack.push(res);
case "*":
var right = stack.pop();
var left = stack.pop();
var res = left * right;
stack.push(res);
case "/":
var right = stack.pop();
var left = stack.pop();
var res = left / right;
stack.push(Math.round(res));
case "@":
var right = stack.pop();
var left = stack.pop();
stack.push(right);
stack.push(left);
}
}
i++;
}
return stack;
}
}