Created
November 7, 2010 04:01
-
-
Save adomokos/665954 to your computer and use it in GitHub Desktop.
A JavaScript Calculator with Closure
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
/* | |
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