Skip to content

Instantly share code, notes, and snippets.

@paxbun
Created November 17, 2019 10:19
Show Gist options
  • Save paxbun/f57d96ad0a50b305522546eae163f262 to your computer and use it in GitHub Desktop.
Save paxbun/f57d96ad0a50b305522546eae163f262 to your computer and use it in GitHub Desktop.
Simple calculator
const ops = "+-*/";
const nums = "0123456789";
function split(expr) {
let rtn = [];
let stack = '';
for (let i = 0; i < expr.length; ++i) {
if (ops.includes(expr[i])) {
rtn.push(stack);
rtn.push(expr[i]);
stack = '';
} else if (nums.includes(expr[i])) {
stack = stack + expr[i];
} else {
return undefined;
}
}
if (stack.length != 0)
rtn.push(stack);
return rtn;
}
function calc(expr) {
if (!expr)
return undefined;
if (expr.length % 2 == 0)
return undefined;
let sum = 0;
let target = Number(expr[0]);
let scale = 1;
for (let i = 1; i < expr.length; i += 2) {
if (expr[i] == '*') {
target *= Number(expr[i + 1]);
} else if (expr[i] == '/') {
target /= Number(expr[i + 1]);
} else if (expr[i] == '+') {
sum += target * scale;
target = expr[i + 1];
scale = 1;
} else {
sum += target * scale;
target = expr[i + 1];
scale = -1;
}
}
sum += target * scale;;
return sum;
}
function run() {
const input = prompt('Put an expression: ');
const result = calc(split(input));
if (result != undefined)
alert(input + '=' + result);
else
alert('Invalid input!');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment