0

I got an assignment where a DB has operator conditions (===, <, >, * etc) to use with some accompanying data.

I need to run those conditions in my JavaScript code. What I found around here is usage of eval or the Function constructor, but both have crucial security and performance issues and are not an option for production code in any sense.

Example:

const operatorFromDB = '>'

const param1FromDB = '10'

const param2FromDB = '5'

But running eval('${param1FromDB}${operatorFromDB}${param2FromDB}') is problematic.

So, how do I actually solve this?

5
  • can you give more context Commented Mar 30, 2023 at 11:45
  • @Teemu added an example in the post. Commented Mar 30, 2023 at 11:50
  • @cmgchess added an example. please let me know if you need anything more Commented Mar 30, 2023 at 11:51
  • how about using logic like if operator is '>' do param1 > param2 and so on. i meant switch statement or if else Commented Mar 30, 2023 at 11:52
  • A popular way is to create an object with operator methods, like ops = {'>': (a, b) => a > b}, then call ex. ops['>'](3, 2). Commented Mar 30, 2023 at 11:54

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.