Learn how to Create a Reverse Polish Notation Calculator in Javascript

0
8

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

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

Choice 1:

``````perform calc(expr) {
var consequence = [];
var atoms = expr.break up(/s+/);
var operators = ['+', '-', '*', '/'];
for (var i=0; i<atoms.size; i++) {
swap(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;
}
``````

Choice 2:

``````perform calc(expr) {
var stack = [];
expr.break 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;
}
``````

Choice 3:

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

Take a look at circumstances to validate our resolution#

``````describe("Checks", () => {
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");
});
});
``````