Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
sisokuenzan
function parse(){
var siki = document.getElementById("z").value;
var s = {
index:0,
f:siki
};
rirekiinsert();
document.getElementById("result").innerHTML= siki + " = " + expr(s).toString();
}
function next(s){
s["index"]++;
while(s["f"].charAt(s["index"])==' '){
s["index"]++;
}
}
function isDigit(c){
if(('0' <= c && '9' >= c) || c == '.'){
return 1;
}
return 0;
}
function num(s){
var start = s["index"]
if(s["f"].charAt(s["index"])=='-' || s["f"].charAt(s["index"])=='+'){
s["index"]++;
}
while(isDigit(s["f"].charAt(s["index"]))){
s["index"]++;
}
var end = s["index"];
while(s["f"].charAt(s["index"])==' '){
s["index"]++;
}
return parseFloat(s["f"].substring(start,end));
}
function fact(s){
if(s["f"].charAt(s["index"]) == '('){
next(s);
var sum = expr(s);
if(s["f"].charAt(s["index"]) == ')'){
next(s);
return sum;
}
}else{
return num(s);
}
}
function term(s){
var sum = fact(s);
while(s["f"].charAt(s["index"]) == '*' || s["f"].charAt(s["index"]) == '/'){
if(s["f"].charAt(s["index"]) == '*'){
next(s);
sum *= fact(s);
}else if(s["f"].charAt(s["index"]) == '/'){
next(s);
sum /= fact(s);
}
}
return sum;
}
function expr(s){
var sum = term(s);
while(s["f"].charAt(s["index"]) == '+' || s["f"].charAt(s["index"]) == '-'){
if(s["f"].charAt(s["index"]) == '+'){
next(s);
sum += term(s);
}else if(s["f"].charAt(s["index"]) == '-'){
next(s);
sum -= term(s);
}
}
return sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment