How to Convert a String into a Math Operator in JavaScript

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 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);.

Convert String into Arithmetic Operator

You are very close:

local execute = {
['+'] = function (x, y) return x + y end,
['-'] = function (x, y) return x - y end,
}
print(execute['+'](2, 2) == 4)

Evaluating a string as a mathematical expression in JavaScript

I've eventually gone for this solution, which works for summing positive and negative integers (and with a little modification to the regex will work for decimals too):

function sum(string) {
return (string.match(/^(-?\d+)(\+-?\d+)*$/)) ? string.split('+').stringSum() : NaN;
}

Array.prototype.stringSum = function() {
var sum = 0;
for(var k=0, kl=this.length;k<kl;k++)
{
sum += +this[k];
}
return sum;
}

I'm not sure if it's faster than eval(), but as I have to carry out the operation lots of times I'm far more comfortable runing this script than creating loads of instances of the javascript compiler



Related Topics



Leave a reply



Submit