Created
March 19, 2021 16:28
-
-
Save uniacid/0737b9345613b02aaa81bbce51690102 to your computer and use it in GitHub Desktop.
String calculator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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