I'm looking for some advice in TDD for my implementation of the String Calculator kata described by Roy Osherov. Any advice regarding refactoring, structuring and polishing of the code is welcome. Still a novice at JS, so please go easy on me.
I have implemented the first 5 rules excluding the delimiter rule. I intend to do this kata everyday as a practice to get better.
The rules for the kata can be found here : http://osherove.com/tdd-kata-1/
Tests :
// StringCalculator-spec.js
describe("String Calculator", function(){
var calculator;
beforeEach(function() {
calculator = new StringCalculator();
});
it("should return zero when '' is passed", function(){
expect(calculator.add('')).toEqual(0);
});
it("should return the number itself when a single number is passed", function(){
expect(calculator.add('1')).toEqual(1);
});
it("should return the sum of the numbers if two are given", function(){
expect(calculator.add('1,2')).toEqual(3);
});
it("should return the sum of an unknown amount of numbers", function(){
// creates a random array
randomArray = (length, max) => [...new Array(length)]
.map(() => Math.round(Math.random() * max));
// creates a random number between 1 and 100
randy = Math.floor((Math.random() * 100) + 1);
res = randomArray(randy,randy);
// sums up an array
sum = res.reduce((pv, cv) => pv+cv, 0);
// converts the array to a string
arg = res.join();
expect(calculator.add(arg)).toEqual(sum);
});
it("should allow \\n in between the input number string", function(){
expect(calculator.add("1\n2,3")).toEqual(6);
});
it("should not allow negative numbers", function(){
expect( function(){ calculator.add("-1,2,3"); } ).toThrow(new Error("negatives not allowed"));
});
});
Code :
// StringCalculator.js
function StringCalculator(){
}
StringCalculator.prototype.add = function(string_numbers) {
this.number = string_numbers;
if (this.number.includes('-')) {
throw new Error('negatives not allowed');
}
// replaces \n with ,
numbers = this.number.replace(/(\r\n|\n|\r)/gm,",");
if (numbers == '') {
return 0;
} else if(numbers.length === 1) {
return (parseInt(numbers));
} else {
res = numbers.split(',');
var total = 0;
var arrayLength = res.length;
for (var i = 0; i < res.length; i++) {
total = total + parseInt(res[i]);
}
return total;
}
};
numbersis not declared withvar,let, orconstcreating a global. \$\endgroup\$