Search code examples
javascriptjquerygoogle-chrome-extension

Convert operator from string type to operator type


I want to generate something like this at random.

233 + 333 = 566

I mean the first number and the operator and the second number are generated at random.

So, I wrote this code now.

var x = parseInt(Math.random()*1000),
    y = parseInt(Math.random()*1000),
    operators = ['+', '-', '*', '/'],
    operatorNum = parseInt(Math.random()*4),
    operator = operators[operatorNum],
    result;

result = x + operator + y;

But this just gives me something like "748/264" as a string. It doesn't give me the result of the calculation generated.

I suppose I need to convert operator from string to operator type. But, I don't think there is a operator type.

Edited

I'm building a Chrome extension. As per the Chrome extension policy, I'm not allowed to use the eval function.


Solution

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