Skip to content

Instantly share code, notes, and snippets.

# inovramadani/mathCalculation.js

Created January 31, 2019 17:20
Show Gist options
• Save inovramadani/d779d5eeb4768be66279de998bd1a4b1 to your computer and use it in GitHub Desktop.
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) }
to join this conversation on GitHub. Already have an account? Sign in to comment