JSFiddle - React, Tailwind, and code Playground
JavaScript
var parse;
parse = function(string){
var index, isDigit, plus, times, unaryMinus, number, peek, advance, consume;
index = 0;
isDigit = function(d){
return '0' <= d && d <= '9';
};
plus = function(){
var str;
str = times();
while (consume("+")) {
str = "(+ " + str + " " + times() + ")";
}
return str;
};
times = function(){
var str;
str = unaryMinus();
while (consume("*")) {
str = "(* " + str + " " + unaryMinus() + ")";
}
return str;
};
unaryMinus = function(){
if (consume("-")) {
return "(- " + number() + ")";
} else {
return number();
}
};
number = function(){
var ret;
if (isDigit(peek())) {
ret = peek();
advance();
while (isDigit(peek())) {
ret += peek();
advance();
}
return ret;
} else {
throw "expected number at index = " + index + ", got " + peek();
}
};
peek = function(){
return string[index];
};
advance = function(){
return index++;
};
consume = function(what){
if (peek() === what) {
advance();
return true;
}
};
return plus();
};
console.log(parse("4+5*6"));
console.log(parse("-4+5"));
console.log(parse("-4*-5+-4"));