Skip to content

Instantly share code, notes, and snippets.

@akkkix
Created May 3, 2017 23:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akkkix/367800d8b79af97e581c5981260d3672 to your computer and use it in GitHub Desktop.
Save akkkix/367800d8b79af97e581c5981260d3672 to your computer and use it in GitHub Desktop.
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