JSFiddle - React, Tailwind, and code Playground
by XTREME104
JavaScript
function Lexem () {
this.type = "";
this.left = "";
this.right = "";
}
function tokenize (input) {
var tokens = [];
var token = "";
for (var i = 0; i < input.length; i++) {
if (input[i] == "(" || input[i] == ")" || input[i] == "*" || input[i] == "/" || input[i] == "+" || input[i] == "-") {
if (token != "") {
tokens.push(token);
token = "";
}
tokens.push(input[i]);
} else {
token += input[i];
}
}
if (token != "") {
tokens.push(token);
token = "";
}
return tokens;
}
function parse (tokens) {
var lexems = tokens;
function lookAhead (text, i) {
for (var j = i; j < lexems.length; j++) {
if (lexems[j] == text) {
return j;
}
}
}
function lookBehind (text, i) {
for (var j = i; j > 0; j--) {
if (lexems[j] == text) {
return j;
}
}
}
function findParens () {
for (var i = 0; i < lexems.length; i++) {
if (lexems[i] == "(" && lookAhead(")", i) < lookAhead("(", i+1)) {
var lexem = parse(tokenize(lexems.slice(i + 1, lookAhead(")", i))));
lexems.splice(i, lookAhead(")", i) - 2, lexem);
console.log(lexems);
}
}
}
function findToken (token) {
for (var i = 0; i < lexems.length; i++) {
if (lexems[i] == token) {
var lexem = new Lexem();
lexem.type = lexems[i];
lexem.left = lexems[i-1];
lexem.right = lexems[i+1];
lexems.splice(i - 1, 3, lexem);
}
}
}
findParens();
findParens();
findToken("*");
findToken("/");
findToken("+");
findToken("-");
return lexems;
}
console.log(parse(tokenize("(0*1+2)+2-(3/4)")));