How one can Create a Reverse Polish Notation Calculator in Javascript

0
0


The problem

Your job is to create a calculator which evaluates expressions in Reverse Polish notation.

For instance expression 5 1 2 + 4 * + 3 - (which is equal to 5 + ((1 + 2) * 4) - 3 in regular notation) ought to consider to 14.

On your comfort, the enter is formatted such {that a} area is supplied between each token.

The empty expression ought to consider to “.

Legitimate operations are +-*/.

It’s possible you’ll assume that there gained’t be distinctive conditions (like stack underflow or division by zero).

The answer in Javascript

Possibility 1:

operate calc(expr) {  
  var end result = [];
  var atoms = expr.cut up(/s+/);
  var operators = ['+', '-', '*', '/'];
  for (var i=0; i<atoms.size; i++) {
    change(atoms[i]) {
      case '+': end result.push(end result.pop() + end result.pop()); break;
      case '-': end result.push(-result.pop() + end result.pop()); break;
      case '*': end result.push(end result.pop() * end result.pop()); break;
      case '/': end result.push(1 /(end result.pop() / end result.pop())); break;
      default: end result.push(parseFloat(atoms[i]));
    }
  }
  return end result.pop() || 0;
}

Possibility 2:

operate calc(expr) {
  var stack = [];
  expr.cut up(" ").forEach(operate(e) {
    if (e === "+") stack.push(stack.pop() + stack.pop());
    else if (e === "-") stack.push(-stack.pop() + stack.pop());
    else if (e === "*") stack.push(stack.pop() * stack.pop());
    else if (e === "/") stack.push(1 / stack.pop() * stack.pop());
    else stack.push(parseFloat(e));
  });
  return stack[stack.length - 1] || 0;
}

Possibility 3:

operate calc(s) {
  var r=/(-?[d.]+) (-?[d.]+) ([-+*/])/
  whereas(s!=""&&r.check(s)) s=s.exchange(r,(_,a,b,op)=>eval(a+op+b))
  return +s.match(/-?[d.]+$/)
}

Take a look at circumstances to validate our answer

describe("Assessments", () => {
  it("check", () => {
    Take a look at.assertEquals(calc(""), 0, "Ought to work with empty string");
    Take a look at.assertEquals(calc("3"), 3, "Ought to parse numbers");
    Take a look at.assertEquals(calc("3.5"), 3.5, "Ought to parse float numbers");
    Take a look at.assertEquals(calc("1 3 +"), 4, "Ought to assist addition");
    Take a look at.assertEquals(calc("1 3 *"), 3, "Ought to assist multiplication");
    Take a look at.assertEquals(calc("1 3 -"), -2, "Ought to assist subtraction");
    Take a look at.assertEquals(calc("4 2 /"), 2, "Ought to assist division");
  });
});

LEAVE A REPLY

Please enter your comment!
Please enter your name here