Similar to python: make a variable equal an operator (+,/,*,-)
I’ve got a bit of code where the user can pick a type of comparison to be run, and a value to compare against. I’m curious to know if there’s any way in Javascript to turn that user provided comparison value into an actual comparison, allowing me to do something like:
if (user_val user_comparison other_val) {
do_something();
}
Instead of having to do something like:
if (user_comparison = '<') {
if (user_val < other_val) {
do_something();
}
else if (user_comparison = '<=') {
if (user_val <= other_val) {
do_something();
}
....etc
Note that should any of the comparisons be matched, the same code will be executed.
No that is not possible. But you can structure your code in a better way. For example you can have a lookup table:
and later:
Of course you should also handle the case when
user_comparisondoes not exist in the table.These also gives you a better control over allowed and not allowed operators.
Here is a DEMO create by @Jesse.