public
Last active

A JavaScript Calculator with Closure

  • Download Gist
JavaScript Calculator with Closure
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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
/*
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);
});
});
});

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.