-
-
Save whois42/16f45f37ad15b929e6af697e0a02ea7c to your computer and use it in GitHub Desktop.
Not fully working code
This file contains 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
const operations = { | |
"+": (num1, num2) => num1+num2, | |
"-":(num1, num2) => num1 - num2, | |
"*": (num1, num2) => num1*num2, | |
"/": (num1, num2) => num1/num2, | |
} | |
const parseString = str => { | |
const resultArr = [] | |
let parentesisBuffer = []; | |
let parentesisBufferActive = false | |
str.split("").forEach((symbol) => { | |
if(symbol === " "){return} | |
if(symbol === "("){ | |
parentesisBufferActive =true | |
return | |
} | |
if(parentesisBufferActive) { | |
if(symbol === ")"){ | |
parentesisBufferActive = false | |
resultArr.push(parentesisBuffer) | |
parentesisBuffer = [] | |
return | |
} else { | |
parentesisBuffer.push(symbol) | |
} | |
} else { | |
resultArr.push(symbol) | |
} | |
}) | |
return resultArr | |
} | |
const calculate = (parsedStr) => { | |
let opsFunc = operations["+"]; | |
return parsedStr.reduce((acc, el) => { | |
if(!isNaN(Number(el))) { | |
return opsFunc(acc,Number(el)) | |
} else if(Object.keys(operations).includes(el)){ | |
opsFunc = operations[el] | |
return acc | |
} else if(Array.isArray(el)) { | |
return opsFunc(calculate(el), acc) | |
} else { | |
throw "unexpected character" | |
} | |
return acc | |
}, 0) | |
} | |
const getResult=(str) => calculate(parseString(str)) | |
let res = calculate(parseString("1+(3+4*2)-1")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment