Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Javascript recursive function to do math calculation on string formula input
// 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