1

Is it possible in javascript to convert a string to an operator?

I'm building a comparator for input in AngularJS.

function comparator(operatorString, value1, value2){
    return value1 converted_operator(operatorString) value2;
}

var myVar1 = comparator("<", 12, 13);//true
var myVar2 = comparator(">=", 12, 13);//false
var myvar3 = comparator("!=" 12, 13);//true

And there are many possible combinations of operators. I could achieve that with an if else. But I would like to know if there is any other alternative for the same.

9
  • 2
    There is no direct way to do that besides eval() (well or via new Function() which is essentially the same thing). Commented Oct 8, 2018 at 15:36
  • You can look intoeval Commented Oct 8, 2018 at 15:36
  • 5
    you could use a mapping with a some kind of dictionary from the string operator to a function, and think in a functional approach. That would imply prewritng a list of accepted functions, which would somehow be similar to several if/else, but maybe a bit more beautiful. and more reusable. Commented Oct 8, 2018 at 15:36
  • I think I'm poor in understanding English or the terms you people are using. Could you please answer it? with various ways to do it. I know eval() from python. Is it the same here? Commented Oct 8, 2018 at 15:38
  • Note that just because you can use eval for this, doesn't mean you should. I'd recommend Pac0's approach. Commented Oct 8, 2018 at 15:38

1 Answer 1

0

Right from the node console:

**> function comparator(operatorString, value1, value2){
    return eval(value1 + operatorString + value2)
   }
undefined
> var myVar1 = comparator("<", 12, 13);
undefined
> myVar1
true
>**
Sign up to request clarification or add additional context in comments.

2 Comments

eval should be used sparingly. Pac0's comment is a safer approach, but if the OP is just fooling around, this does work.
Agree with Jonathan. it's not recommended.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.