Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
A JavaScript Calculator with Closure
/*
function Calculator() {
this.add = function(input) {
var result = 0;
for(i = 0; i<input.length; ++i) {
result += input[i];
}
return result;
}
this.multiply = function(input) {
var result = 1;
for(i=0; i<input.length; ++i) {
result *= input[i];
}
return result;
}
}
*/
function Calculator() {
var operator = function(result, input) { return result + input; };
this.add = function(input){
return operation(input, operator);
};
this.multiply = function(input){
return operation(input, function(result, input) { return result * input; });
}
this.subtract = function(input){
return operation(input, function(result, input) { return result - input; });
}
this.divide = function(input){
return operation(input, function(result, input) { return result / input; });
}
function operation(input, operator) {
var result = input.shift();
for(i = 0; i < input.length; i++){
result = operator(result, input[i]);
}
return result;
}
}
describe("Calculator", function() {
var calculator;
beforeEach(function() {
calculator = new Calculator();
});
describe("Arithmetic operations on an array input", function() {
it("creates a new Calculator object", function() {
expect(calculator).not.toBeNull();
});
it("adds two numbers together", function() {
expect(calculator.add([1,0])).toEqual(1);
});
it("adds three numbers together", function() {
expect(calculator.add([1,2,3])).toEqual(6);
});
it("multiplies two numbers", function(){
expect(calculator.multiply([1,2])).toEqual(2);
});
it("returns the difference between the numbers passed in", function(){
expect(calculator.subtract([3,2])).toEqual(1);
});
it("returns the quotient of the numbers passed in", function(){
expect(calculator.divide([10,2,5])).toEqual(1);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.