tags:

views:

113

answers:

3

Hello, I'm trying to make a Javascript function that will take a math equation and do it on a predefined number for example:

var myNum = 10;

function EQ(eq){
// code here 
}

For example the input should me something like this:

EQ("*100/10"); //output 100
EQ("+100");    //output will be 200
EQ("-+=1");    //output false

Is there any way to do that? Thanks

+3  A: 

You could probably work eval() into a simple solution. For instance:

var myNum = 10;

function EQ(eq) { return eval(myNum+eq); }

alert( EQ("*100/10") ); // outputs 100

I'd encourage you to expand upon this by implementing a try-catch and handling exceptions.

Jonathan Sampson
thanks a lot, but EQ("100/10"); // output 1010 // how to output an error ??
From.ME.to.YOU
@From.ME You are changing syntax on me here. All of your examples started with an operator in the value passed to `EQ()`. In the data you provided, and in my solution, it is assumed the first char will always (without variance) be an operator. If you pass in `100/10` then the evaluated expression will be `10100/10`, which is `1010`.
Jonathan Sampson
With regards to error-handling, here is some information on the `Try...Catch` in Javascript: http://www.w3schools.com/js/js_try_catch.asp
Jonathan Sampson
A: 

try this...

function EQ(input) {
  try {
    var ret = Number(eval('(0+(' + input + '))'));
    return isNaN(ret) ? null : ret;
  } catch(err) {
  }
  return null;
}

You can replace the null default with a literal false if you like...

Tracker1
+1  A: 

Here's a simple expression evaluator:

function evalExpression(text)
{
  var tokens = text.split(" ");

  var output = [];
  var operators = [];

  var reNumber = /^\d+(\.\d+)?$/;
  var reOperator = /^[\/\+\*\-]$/;
  var precedence = { "+": 1, "-": 1, "*": 2, "/": 2 };

  for (var i = 0; i < tokens.length; ++i)
  {
    var t = tokens[i];
    if (reNumber.test(t))
      output.push(Number(t));
    else if (reOperator.test(t))
    {
      while (operators.length && precedence[t] <= precedence[operators[operators.length - 1]])
      {
        output.push(operators.pop());
      }

      operators.push(t);
    }
    else if (t == "(")
      operators.push(t);
    else if (t == ")")
    {
      while (operators.length && operators[operators.length - 1] != "(")
        output.push(operators.pop());

      if (!operators.length) return false;

      operators.pop();    
    }
    else 
      return false;
  }

  while (operators.length)
    output.push(operators.pop());

  var result = [];

  for (i = 0; i < output.length; ++i)
  {
    t = output[i];
    if (reNumber.test(t))
      result.push(t);
    else if (t == "(" || result.length < 2)
      return false;
    else 
    {
      var lhs = result.pop();
      var rhs = result.pop();

      if (t == "+") result.push(lhs + rhs);
      if (t == "-") result.push(lhs - rhs);
      if (t == "*") result.push(lhs * rhs);
      if (t == "/") result.push(lhs / rhs);
    }
  }

  return result.pop();
}

It supports numbers and + - * / ( ). Tokens must be separated by a single space, e.g.: "1 * ( 2 + 3 )"

Anyway, that's the type of code you'd need if you didn't want to use eval.

konforce