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()

horns
  • 1,805
  • 1
  • 19
  • 25
The Mask
  • 16,429
  • 36
  • 107
  • 177
  • Looks like one of the few cases where `eval()` would be handy. – alex Sep 09 '11 at 01:03
  • Is `new Function()` off limits too? – alex Sep 09 '11 at 01:07
  • Why not using `eval()` out of curiosity? – Demian Brecht Sep 09 '11 at 01:10
  • You might find the following series interesting: [Essentials of Interpretation](https://github.com/DmitrySoshnikov/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. – Christian C. Salvadó Sep 09 '11 at 01:20

3 Answers3

6

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));
Community
  • 1
  • 1
Joe
  • 15,441
  • 4
  • 43
  • 81
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;
  }
}
Mike Samuel
  • 114,030
  • 30
  • 209
  • 240
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);
});
maerics
  • 143,080
  • 41
  • 260
  • 285