-1

I would like to create function what does this:

const doMath = (operator) => {
    return 5 operator 2;
}

doMath('+')
doMath('-')

I was thinking on something like that:

const doMath = (operator) => {
    return 5 (operator === '+' ? + : -) 2;
}

But I am missing something.

  • This is what eval() is for - but be very careful! – Mike Brockington May 24 '22 at 10:28
  • I don't think you can achieve what you are trying to do in any way. In JavaScript operators get parsed in the pre-parse phase, and they have to follow a precise syntax. – Cristian Traìna May 24 '22 at 10:30
  • Yeah, Mike is right, don't go down that path. Use a switch and small functions for the arithmetic. – zer00ne May 24 '22 at 10:32
  • The closest solution would be creating two functions `sum` and `diff`, and then apply one of them with ternary operations: `const sum = (a,b) => a+b; const diff = (a,b) => a-b; (operator === '+' ? sum : diff)(5, 2)` – Cristian Traìna May 24 '22 at 10:32

0 Answers0