Stokres
Stokres

Reputation: 685

How to user a condition in a String inside an IF sentence

I have the following situation:

var answer = 'three';
var isClosed = true;
var condition = "answer != null && !isClosed";

The condition is a literal string and it's dynamically set by the user. Once they set the condition, I need to evaluate it inside an IF/ELSE sentence:

if(condition)
   //Do something
else
   //Do something

Can I do that without using "eval()"? How? I want to avoid it:

if(eval(condition))
...

NOTE: This is a simple example, the real situation is a bit complex with dynamic conditions :)

Upvotes: 0

Views: 64

Answers (2)

Mironor
Mironor

Reputation: 1187

If you want to evade eval at all cost (as it can be really dangerous for the security reasons), you basically need a rules engine adapted to your dsl that you get from the database.

I googled this one and it seems prety decent C2FO , didn't actually tried it, but now you know where to start.

Upvotes: 1

shakirthow
shakirthow

Reputation: 1366

A bit confused.. But if the answer and isClosed set by the user.. then just something like this will suffice..

answer = null
isClosed = false // the default value for isClosed
if(answer != null && !isClosed){
  //Do something
}
else{
   //Do something
}

Upvotes: 0

Related Questions