Skip to content

Instantly share code, notes, and snippets.

@stupakov
Created June 24, 2011 06:01
Show Gist options
  • Save stupakov/1044304 to your computer and use it in GitHub Desktop.
Save stupakov/1044304 to your computer and use it in GitHub Desktop.
// Calculator Constructor
var Calculator = function() {
//private
var q = [0];
var makeRpnFunction = function(op) {
return function() {
var v1 = q.pop();
if (v1 == undefined) {
throw new Error('calculator is empty');
} else {
var v2 = q.pop();
if (v2 == undefined) {
q.push(v1); /* put v1 back if we fail to get a v2 */
throw new Error('calculator is empty');
} else {
q.push(op(v2, v1));
};
};
};
};
//public
this.value = function() {
return q[q.length-1];
};
this.add = function(v) {
q[q.length-1] += v;
};
this.subtract = function(v) {
q[q.length-1] -= v;
};
this.push = function(v) {
q.push(v);
};
this.plus = makeRpnFunction( function(a, b) { return a + b; } );
this.minus = makeRpnFunction( function(a, b) { return a - b; } );
this.divide = makeRpnFunction( function(a, b) { return a / b; } );
this.times = makeRpnFunction( function(a, b) { return a * b; } );
};
// I've added one more item to the spec - the implementation above meets this requirement also:
describe("using reverse polish notation", function() {
// ...
it("does not change value if an RPN operation fails when < 2 values are on the stack", function() {
expect(function() {
calculator.plus();
}).toThrow("calculator is empty");
expect(calculator.value()).toEqual(0);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment