Tuesday, April 23, 2024
HomeSoftware EngineeringTips on how to Create a Reverse Polish Notation Calculator in Javascript

Tips on how to Create a Reverse Polish Notation Calculator in Javascript


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.

In 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 +-*/.

Chances are you’ll assume that there received’t be distinctive conditions (like stack underflow or division by zero).

The answer in Javascript

Possibility 1:

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

Possibility 2:

perform calc(expr) {
  var stack = [];
  expr.cut up(" ").forEach(perform(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:

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

Take a look at circumstances to validate our resolution

describe("Assessments", () => {
  it("take a look at", () => {
    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 help addition");
    Take a look at.assertEquals(calc("1 3 *"), 3, "Ought to help multiplication");
    Take a look at.assertEquals(calc("1 3 -"), -2, "Ought to help subtraction");
    Take a look at.assertEquals(calc("4 2 /"), 2, "Ought to help division");
  });
});
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments