Javascript recursive function to do math calculation on string formula input
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
// recursive function to do math calculation on string formula input | |
// use case: mathCalculation("1 * 2 + 4 / 2 - 6") | |
function mathCalculation (formula) { | |
const plusOperator = '+' | |
const minusOperator = '-' | |
const multiplyOperator = '*' | |
const divideOperator = '/' | |
if (formula.indexOf(plusOperator) > 0) { | |
const operands = formula.split(plusOperator) | |
let total = 0 | |
operands.forEach(operand => { | |
total = total + mathCalculation(operand) | |
}) | |
return total | |
} | |
else if (formula.indexOf(minusOperator) > 0) { | |
const operands = formula.split(minusOperator) | |
let total = 0 | |
operands.forEach((operand, index) => { | |
if (index === 0) { | |
total = mathCalculation(operand) | |
} | |
else { | |
total = total - mathCalculation(operand) | |
} | |
}) | |
return total | |
} | |
else if (formula.indexOf(multiplyOperator) > 0) { | |
const operands = formula.split(multiplyOperator) | |
let total = 1 | |
operands.forEach(operand => { | |
total = total * mathCalculation(operand) | |
}) | |
return total | |
} | |
else if (formula.indexOf(divideOperator) > 0) { | |
const operands = formula.split(divideOperator) | |
let total = 1 | |
operands.forEach((operand, index) => { | |
if (index === 0) { | |
total = mathCalculation(operand) | |
} | |
else { | |
total = total / mathCalculation(operand) | |
} | |
}) | |
return total | |
} | |
return Number(formula) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment