Are Variable Operators Possible?
50,845
Solution 1
We can implement this using eval
, since we are using it for operator checking.
var number1 = 30;
var number2 = 40;
var operator = '===';
function evaluate(param1, param2, operator) {
return eval(param1 + operator + param2);
}
if (evaluate(number1, number2, operator)) {}
in this way we can use dynamic operator evaluation.
Solution 2
I believe you want a variable operator. here's one, created as object. you can change the current operation by changing:
[yourObjectName].operation = "<" //changes operation to less than
function VarOperator(op) { //you object containing your operator
this.operation = op;
this.evaluate = function evaluate(param1, param2) {
switch(this.operation) {
case "+":
return param1 + param2;
case "-":
return param1 - param2;
case "*":
return param1 * param2;
case "/":
return param1 / param2;
case "<":
return param1 < param2;
case ">":
return param1 > param2;
}
}
}
//sample usage:
var vo = new VarOperator("+"); //initial operation: addition
vo.evaluate(21,5); // returns 26
vo.operation = "-" // new operation: subtraction
vo.evaluate(21,5); //returns 16
vo.operation = ">" //new operation: ">"
vo.evaluate(21,5); //returns true
Solution 3
You can use the eval()
function, but that is not a good idea.
I think the better way is writing functions for your operators like this:
var addition = function(first, second) {
return first+second;
};
var subtraction = function(first, second) {
return first-second;
};
var operator = addition;
alert(operator(12, 13));
var operator = subtraction;
alert(operator(12, 13));
Solution 4
A bit newer approach. It can be done pretty decent using currying:
const calculate = a => str => b => {switch(str) {
case '+': return a + b
case '-': return a - b
case '/': return a / b
case '*': return a * b
default: return 'Invalid operation'
}}
const res = calculate(15)('*')(28)
console.log('15 * 28 =', res)
Solution 5
You can't overload operators in JavaScript. You can off course use functions to help
var plus = function(a, b) {
return a + b;
};
var smaller = function(a, b) {
return a < b;
};
var operator = plus;
var total = operator(a, b);
operator = smaller;
if(operator(var1, var2)){ /*do something*/ }
Comments
-
Gary almost 2 years
Is there a way to do something similar to either of the following:
var1 = 10; var2 = 20; var operator = "<"; console.log(var1 operator var2); // returns true
-- OR --
var1 = 10; var2 = 20; var operator = "+"; total = var1 operator var2; // total === 30
-
karan bhatia almost 3 yearsThank you!!!!!!!! I like this approach. Much cleaner
-
Callam about 2 yearsBig security risk - developer.mozilla.org/en-US/docs/web/javascript/reference/…!