Turn String into Operator

Turn string into operator

Use a lookup table:

import operator
ops = { "+": operator.add, "-": operator.sub } # etc.

print(ops["+"](1,1)) # prints 2

How to convert a string into an operator in javascript?

You could use the Function constructor, but your shouldn't, as it will attempt to run any arbitrary code contained within the string. A safer choice would be to use a switch statement and whitelist the supported operations -

function applyOperator(op, a, b)
{ switch (op)
{ case "+": return a + b
case "-": return a - b
case "*": return a * b
case "/": return a / b
case "%": return a % b
case "^": return Math.pow(a, b)
default: throw Error(`unsupported operator: ${op}`)
}
}

console.log(applyOperator("*", 3, 5))
console.log(applyOperator("-", 3, 5))
console.log(applyOperator("+", 3, 5))
console.log(applyOperator("!", 3, 5))

Convert String to operator(+*/-) in java

probably the best way to do it will be equals, but it's best to ignore whitespaces:

i'm not quite sure how you split your string, but for example, if you have a char op and two integer a and b:

String str = op.replace(" ", "");

if(str.equals("*")){
retVal = a*b;
} else if(str.equals("+")){
retVal = a+b;
}//etc

JavaScript convert string to operator

You can define an object with the string representation of operators as properties that return an arrow function performing the corresponding comparison.

const compare = {
'==': (a, b) => a == b,
'!=': (a, b) => a != b,
'===' : (a, b) => a === b,
'!==' : (a, b) => a !== b
}

const obj1 = 1;
const obj2 = 2;

console.log(compare['=='](obj1, obj2))
console.log(compare['!='](obj1, obj2))
console.log(compare['==='](obj1, obj2))
console.log(compare['!=='](obj1, obj2))

Convert operator from string type to operator type

Evaluate it:

result = eval(x + operator + y);

EDIT

Since you can't use eval, you need to build your own math functions. You can just specify the four functions inside that array (if you don't actually need to know their names), like:

myFunctions = [
function(a, b){return a+b;},
function(a, b){return a-b;},
function(a, b){return a/b;},
function(a, b){return a*b;}
];

Then just randomly pick one and call it with your x and y variables as parameters, just like you did before: result = myFunctions[parseInt(Math.random()*4)](x, y);.



Related Topics



Leave a reply



Submit