2

I tried to write a computation mathematical expression and store each sign into an array.

For example, I want to convert the array:

let arr = ['10', '-', '(', '2', '+', '1', ')', '*', '3'];

To the following expression:

let result = 10 - (2 + 1) * 3;  // 1

Any suggestions on how to achieve this?

Maor Refaeli
  • 2,417
  • 2
  • 19
  • 33
Raymond Yeh
  • 255
  • 2
  • 6
  • 23
  • 1
    `eval(arr.join(' '))` – Nenad Vracar Aug 28 '18 at 13:39
  • Mate I corrected it. You haven't clicked new changed link. – Rahul Aug 28 '18 at 13:42
  • You can create your own calculator as well. We did it in college to practice stacks (for arrays it's the use of `push` and `pop`). Pretty much you keep pushing numbers to one array and operators to the other array. When you find something that has higher precedence, you handle it in place. You do this until the arrays are empty. – Matt Aug 28 '18 at 16:42
  • Yes, that is what I practice currently :) – Raymond Yeh Aug 28 '18 at 22:09

2 Answers2

2

It will not validate your input but eval(arr.join("")) will do it.
eval takes a string and executes it as it were a js expression.

Maor Refaeli
  • 2,417
  • 2
  • 19
  • 33
  • I forgot I can use eval() to achieve this goal. Thank you so much – Raymond Yeh Aug 28 '18 at 13:43
  • No problem, but keep in mind that this will only work if the expression is valid. Also, consider reading [this](https://stackoverflow.com/a/198031/1918287) before using `eval`. – Maor Refaeli Aug 28 '18 at 13:44
2

It work only with eval,

new Function is not working for this issue

const arr = ['10', '-', '(', '2', '+', '1', ')', '*', '3'];

eval(arr.join(' ')); // 1
Community
  • 1
  • 1
аlex
  • 5,426
  • 1
  • 29
  • 38