-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpn
57 lines (42 loc) · 1.19 KB
/
rpn
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
function RPNCalculator(){ //stack
this.stack = [];
}
RPNCalculator.prototype.push = function(value){ //input
this.stack.push(value);
};
RPNCalculator.prototype.popcompute = function(operatorfunc){ //generic function operator
if(this.stack.length < 2 ){
throw 'rpnCalculatorInstance is empty';
}else{
var num1 = this.stack.pop();
var num2 = this.stack.pop();
this.push(operatorfunc(num1,num2));
}
};
RPNCalculator.prototype.plus = function(){ //plus operator
var add = function (a,b){
return b + a;
};
this.popcompute(add);
};
RPNCalculator.prototype.minus = function(){ //subtract operator
var subtract = function(a,b){
return b - a;
};
this.popcompute(subtract);
}
RPNCalculator.prototype.times = function(){ //multiplication operator
var multiplies = function(a,b){
return b * a;
};
this.popcompute(multiplies);
}
RPNCalculator.prototype.divide = function(){ //division operator
var divide = function(a,b){
return b / a;
}
this.popcompute(divide);
}
RPNCalculator.prototype.value = function(){ //returns the top value
return this.stack[this.stack.length-1];
}