Skip to content

Instantly share code, notes, and snippets.

@uniacid
Created March 19, 2021 16:28
Show Gist options
  • Save uniacid/0737b9345613b02aaa81bbce51690102 to your computer and use it in GitHub Desktop.
Save uniacid/0737b9345613b02aaa81bbce51690102 to your computer and use it in GitHub Desktop.
String calculator
//10+5*2
const str = '10+5*2';
let total = 0;
let currentNum = '';
let operator = '';
for (var i = 0; i < str.length; i++) {
if (parseInt(str[i]) > -1) {
currentNum = currentNum + str[i];
} else {
if (str[i] !== '') {
operator = str[i];
}
// total = currentNum;
currentNum = '';
}
if (total >= 0 && currentNum > 0 && operator !== '') {
if (operator === '+') {
total = parseInt(total) + parseInt(currentNum);
}
if (operator === '*') {
total = parseInt(total) * parseInt(currentNum);
}
operator = '';
} else {
if (currentNum > 0) {
total = currentNum;
}
}
}
console.log('string total', total);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment