-4

How can I accept a formula from an input field to calculate a value? For example "(a+b)/100", "(a*b)/300" "(b/a)", etc.

The result should be the calculated value. So, given A = 100; B = 200; and the formula is "(a+b)", the result should be 300.

JakeParis
  • 11,056
  • 3
  • 42
  • 65
sumit
  • 11
  • 1
  • 4
  • You can use [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) – Karan Jun 08 '20 at 10:49

2 Answers2

0

You can use eval which is actually not recommended. Create an object inside the function where the operator name is the key and symbol is the value like + or *. While calling the function pass an object with two values and the operator.

function doCalculation({
  val1,
  val2,
  operation
}) {
  const obj = {
    add: '+',
    multiply: '*'
  }
  return parseInt(eval(`${val1}${obj[operation]}${val2}`), 10) / 100
}

console.log(doCalculation({
  val1: 100,
  val2: 200,
  operation: 'add'
}))
brk
  • 48,835
  • 10
  • 56
  • 78
0

I would recommend using one of the existing libraries for parsing & evaluating equations.
There are quite a few of them available on npm.

For example expr-eval:

const parser = new exprEval.Parser();
const expr = parser.parse("(a+b)/100");
console.log(expr.evaluate({ a: 100, b: 200 })); // 3
console.log(expr.evaluate({ a: 200, b: 200 })); // 4
<script src="https://unpkg.com/expr-eval@1.2.2/dist/bundle.min.js"></script>

Not only is this more robust than an eval-based approach, but it also uses a more math-oriented syntax in comparison to javascript.

Turtlefight
  • 9,420
  • 2
  • 23
  • 40