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
Jquery Get Values of Checked Checkboxes into Array
Property 'Value' Does Not Exist on Type Eventtarget in Typescript
How to Make a JSON Call to an Url
Converting JSON Results to a Date
Convert an Image into Binary Data in JavaScript
Difference Between Dot Notation and Bracket Notation in JavaScript
Javascript/Jquery Check Broken Links
How to Handle Circular Dependencies with Requirejs/Amd
How to Load the Web Page Content Based on User Scrolling
How to Prevent Simultaneous Logins of the Same User with Firebase
How to Set Image Source with Base64
Reactjs Syntheticevent Stoppropagation() Only Works with React Events
Downloading Canvas Element to an Image
Why Do Arrow Functions Not Have the Arguments Array
How Do the JavaScript Relational Comparison Operators Coerce Types
ASP.NET MVC 3 Razor: Include JavaScript File in the Head Tag
Differences Between Contenttype and Datatype in Jquery Ajax Function