Skip to content

Instantly share code, notes, and snippets.

@simon0191
Created December 6, 2014 20:28
Show Gist options
  • Save simon0191/ccf93f83085a9b479b65 to your computer and use it in GitHub Desktop.
Save simon0191/ccf93f83085a9b479b65 to your computer and use it in GitHub Desktop.
function main(str) {
var ssT = /[\*\+\-\/]/;
var nsT = /\d/;
var ns = str.split(ssT).filter(function(s) {
return s !== '';
});
var ss = str.split(nsT).filter(function(s) {
return s !== '';
});
console.log(ns);
console.log(ss);
var hasTimes = true;
while(hasTimes) {
hasTimes = false;
for(var i = 0;i<ss.length;++i) {
if(ss[i] ==='*') {
hasTimes = true;
ns.splice(i,2,parseFloat(ns[i]) * parseFloat(ns[i+1]));
ss.splice(i,1);
console.log(ns);
console.log(ss);
break;
} else if(ss[i] ==='/') {
hasTimes = true;
ns.splice(i,2,parseFloat(ns[i]) / parseFloat(ns[i+1]));
ss.splice(i,1);
console.log(ns);
console.log(ss);
break;
}
}
if(!hasTimes) break;
}
while(ns.length > 1) {
for(var i = 0;i<ss.length;++i) {
if(ss[i] ==='+') {
ns.splice(i,2,parseFloat(ns[i]) + parseFloat(ns[i+1]));
ss.splice(i,1);
break;
} else if(ss[i] ==='-') {
ns.splice(i,2,parseFloat(ns[i]) - parseFloat(ns[i+1]));
ss.splice(i,1);
break;
}
}
}
return ns[0];
}
console.log(main("4+5+6+5/8*6"));
console.log(main("1+2/8*4-4"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment