Skip to content

Instantly share code, notes, and snippets.

@akingdom
Last active May 30, 2021 20:17
Show Gist options
  • Save akingdom/830b5b71baa52bac0e9bb479db337950 to your computer and use it in GitHub Desktop.
Save akingdom/830b5b71baa52bac0e9bb479db337950 to your computer and use it in GitHub Desktop.
precedence
//application/javascript
//
// A simple sequential calculator.
// By Andrew Kingdom
// MIT license
//
// Operator order/precedence is ignored.
// The calculation string is expected to have numbers and operators separated by spaces.
//
function operate(x,oper,y) {
console.log('x:' + x + ' oper:' + oper + ' y:' + y);
if(oper == '') {
answer = y; // no operator -- reset result
} else {
answer = eval(x+oper+y);
}
console.log(' =' + answer);
return answer;
}
function calc(str) {
tokens = str.split(' '); // space delimited tokens
operator = '';
result = 0;
for(let token of tokens){
number = parseFloat(token);
if(!isNaN(number))
result = operate(result,operator,number);
else if('+/*-'.indexOf(token) != -1)
operator = token;
else
return 'invalid token';
}
return result;
}
console.log(
"The result is: " + calc('2 + 3 + 35 / 68 / 9 * 37 - 8 + 67 + 9'));
/* OUTPUT:
x:0 oper: y:2
=2
x:2 oper:+ y:3
=5
x:5 oper:+ y:35
=40
x:40 oper:/ y:68
=0.5882352941176471
x:0.5882352941176471 oper:/ y:9
=0.06535947712418301
x:0.06535947712418301 oper:* y:37
=2.4183006535947715
x:2.4183006535947715 oper:- y:8
=-5.5816993464052285
x:-5.5816993464052285 oper:+ y:67
=61.41830065359477
x:61.41830065359477 oper:+ y:9
=70.41830065359477
The result is: 70.41830065359477
*/
Copy link

ghost commented May 30, 2021

that's cool man, a lovely tool for maths student like me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment