Skip to content

Instantly share code, notes, and snippets.

@inovramadani
Created January 31, 2019 17:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inovramadani/d779d5eeb4768be66279de998bd1a4b1 to your computer and use it in GitHub Desktop.
Save inovramadani/d779d5eeb4768be66279de998bd1a4b1 to your computer and use it in GitHub Desktop.
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