Created
June 24, 2011 06:01
-
-
Save stupakov/1044304 to your computer and use it in GitHub Desktop.
Example of Calculator Constructor for https://github.com/blazingcloud/javascript_lessons/tree/master/05_calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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