3

for example:

var s = '3+3';
s.replace(/([\d.]+)([\+\-)([^,]*)/g,
        function(all, n1, operator, n2) {
                r = new Number(n1) ??? new Number(n2);
                return r;
        }
);

note: not using eval()

4
  • Looks like one of the few cases where eval() would be handy. Commented Sep 9, 2011 at 1:03
  • Is new Function() off limits too? Commented Sep 9, 2011 at 1:07
  • Why not using eval() out of curiosity? Commented Sep 9, 2011 at 1:10
  • You might find the following series interesting: Essentials of Interpretation. They are small lesson about computer program interpretation, written in Javascript, the goal at the end IMO will be to implement a small scheme-like language. Commented Sep 9, 2011 at 1:20

3 Answers 3

7

Are Variable Operators Possible?

Not possible out of the box, but he gives a nice implementation to do it, as follows. Code by delnan.

var operators = {
    '+': function(a, b) { return a + b },
    '<': function(a, b) { return a < b },
     // ...
};

var op = '+';
alert(operators[op](10, 20));

So for your implementation

r = operators[operator](new Number(n1), new Number(n2));
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for using the object to look up operator functions instead of if/else or switch/case.
1

Your regex is a bit broken.

/([\d.]+)([\+\-)([^,]*)/g

should probably be

/([\d.]+)([+-])([\d+]+)/g

then you can switch on the operator:

function (_, a, op, b) {
  switch (op) {
    case '+': return a - -b;
    case '-': return a - b;
  }
}

Comments

0
s.replace(/(\d+)\s*([+-])\s*(\d+)/g, function(all, s1, op, s2) {
  var n1 = Number(s1), n2 = Number(s2);
  return (op=='+') ? (n1+n2) : (n1-n2);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.